Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.Find with Delegate. What does it return if not found?

I have an Array<Person> myArray and I am using the following code

myArray.Find(o => o.name.Equals("John"));

This article in Msdn states:

Return Value

Type: T

The first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T.

If I had an Array<int> the default value would be zero. But, in my case I am using a class. Let's say Array<Person>.

What would be the default for my class and how can I handle the not found case using a delegate?

like image 575
Odys Avatar asked Jul 31 '11 21:07

Odys


People also ask

Does array find return a copy?

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. Whether it returns a copy of or a reference to the value will follow normal JavaScript behaviour, i.e. it'll be a copy if it's a primitive, or a reference if it's a complex type.

How do you check if a value is present in an array C#?

Use the Equals method to check if an item exists in a C# array. string subStr = "pqrs"; string[] str = { "abcd", "ijkl", "pqrs", "wxyz" }; Now check whether the substring is part of the string or not using the Equals method.

How to search through an array in C#?

Use the Array. Find() or Array. FindAll() or Array. FindLast() methods to search for an elements that match with the specified condition.


2 Answers

Assuming Person is a reference type, the default value for it would be null.

Therefore the call to Array.Find() would return null when the condition wasn't satisfied.

like image 162
tomfanning Avatar answered Nov 08 '22 04:11

tomfanning


The default for any reference type (class, interface, delegate) is a null reference. The default for any value type is a value where all the fields of the type are the default value for that field - so you end up with 0, \0, false etc.

See MSDN for more details.

like image 35
Jon Skeet Avatar answered Nov 08 '22 05:11

Jon Skeet