C
C
CSharpMutant2021-05-05 12:41:36
Arrays
CSharpMutant, 2021-05-05 12:41:36

What are the pros and cons of the methods? What is better to use?

array[Length-1] or array[^1]?
Ways to find the end of an array.6092684a96b84957897320.jpeg

Answer the question

In order to leave comments, you need to log in

5 answer(s)
V
Vasily Bannikov, 2021-05-05
@vabka

It is better to use the second option.
The only downside is that it won't work on older versions of the language.
But I would use .Last()

D
Developer, 2021-05-05
@samodum

It is better to use the first option. It is only necessary to add a check that length > 0
will work on all versions of the language, and does not affect performance in any way

V
Vladimir Korotenko, 2021-05-05
@firedragon

The code is written for people, for example, only after looking at the documentation I realized what the ^ operator does,
therefore either option 1 or
.Last() is preferable

D
Dmitry Pavlov, 2021-05-05
@Stalker31

Use the one you better remember

C
cicatrix, 2021-05-06
@cicatrix

[^1] is syntactic sugar.
If you look at how this code looks in IL, it turns out that the same code is being executed.
Who doubts, here:
Translation to IL
For understanding and subsequent support, it is better to use array[Length-1]. This is more clear and understandable, maybe in a few years the [^1] syntax will become more recognizable and widespread, but so far this is not the case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question