I have a method that searches a list of objects based on some of the fields of the object. If a matching object is found, I return it, but I want to be able to represent a no-match situation. Normally I'd return null but I'm working with a non-nullable class I cannot change.
Asked
Active
Viewed 55 times
3 Answers
4
There are several options. Use a Nullable<T>
, or return a bool and use an out
parameter to get the actual result, e.g.:
MyType? FindObject() { }
Or:
bool FindObject(out MyType result) { }

Sven
- 21,903
- 4
- 56
- 63
0
This situation can be handled by Null Pattern.
What confuse me is that you wrote that you return list of objects and then object. Could you give some details ?

Damian Leszczyński - Vash
- 30,365
- 9
- 60
- 95
0
Can you throw an exception? NoObjectFoundException

gfelisberto
- 1,655
- 11
- 18
-
This is not a good idea. Exceptions have quite a heavy performance impact and should not be be thrown as part of normal program flow (they are for exceptional situations only). – Sven Jun 07 '11 at 16:50