This seems like a silly question, but I haven't found the answer, so here it is. :)
In both cases, you will get an "out-of-range" exception if you fail to check the bounds of your collection. Is this just coding style preference?
And in case someone needs an example:
List<byte> myList = new List<byte>(){0x01, 0x02, 0x03}; byte testByte = myList.ElementAt(2);
versus
byte testByte = myList[2];
ElementAt() is a System. Linq method in C# that is used to get and display element at a particular index. The following is our string array − string[] arr = { "One", "Two", "Three", "Four", "Five" }; Now to get an element at index 0, use the ElementAt() method − arr.ElementAt(0); The following is the complete code −
ElementAtOrDefault<TSource>(IEnumerable<TSource>, Index) Returns the element at a specified index in a sequence or a default value if the index is out of range.
Because Enumerable
is more generic, and a collection represented by enumerable may not have an indexer.
But, if it does - don't use ElementAt()
it's probably not going to be as efficient.
ElementAt()
provides a unified interface for all enumerations in C#. I tend to use it quite often as I like the common API.
If the underlying type supports random access (ie, it supports the []
operator), then ElementAt will make use of that. So the only overhead is an extra method call (which is almost never relevant).
If the underlying type does not support random access, then ElementAt()
simulates it by iterating the enumeration until it arrives at the element you care about. This can be very expensive and even have side effects sometimes.
There is also ElementAtOrDefault()
which is often very handy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With