Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a practical reason for why List<T>.IndexOf(T) does not return a nullable int? [closed]

Tags:

c#

list

nullable

The method List<T>.IndexOf() returns the zero-based index of the first occurrence of item within the entire List, if found; otherwise, –1.

I'm seeing a parallel between that, and something I just read in Code Complete, which is telling me to "avoid variables with hidden meanings".

For example: The value in the variable pageCount might represent the number of pages printed, unless it equals -1, in which case it indicates that an error has occurred.

Well, I don't know if the meaning is "hidden", because it's documented clearly enough, but null seems to convey better meaning to me than -1, and .HasValue reads like a much better check than > -1. As far as I can tell, List and nullable types were both introduced in C# 2.0, so I don't think the reason for retuning an int has to do with backwards compatibility. So, do you know if there was a reason, or if this was just something that someone forgot to implement, and we now have to live with that mistake forever?

like image 774
Jessy Avatar asked Jun 02 '12 18:06

Jessy


People also ask

What does IndexOf return if not found C#?

In C#, IndexOf() method is a string method. This method is used to find the zero-based index of the first occurrence of a specified character or string within the current instance of the string. The method returns -1 if the character or string is not found.

Does list have Index C#?

The IndexOf method returns the first index of an item if found in the List. C# List<T> class provides methods and properties to create a list of objects (classes). The IndexOf method returns the first index of an item if found in the List.

How do you get the index of an item in a list C#?

To get the index of an item in a single line, use the FindIndex() and Contains() method. int index = myList. FindIndex(a => a.


1 Answers

List was released with the 2.0 version of the run time as was nullable T. But List implements IList which existed with the 1.0 version of the runtime which not only didn't have nullable it didn't support generics. To meet the contract of the IList interface an implementer must return -1 on indexof failure. Code complete also maintains that you must meet the contracts you agree to and therefore List.Indexof must return -1.


Answer to Comment:

By the time the 2.0 runtime with generics there were already thousands of applications written against the non generic version. That code would be allowed to function most effectively be migrated by supporting the generic interface as an extension of the non-generic interfaces. Also, image having to classes with the same name and 90% same usage but in the case of a couple of methods totally different semantics.

like image 122
rerun Avatar answered Nov 15 '22 16:11

rerun