It’d be nice if I could define a method like this:
public T GetItem<T>() where T : null
{
if (someCondition<T>())
return someCalculation<T>();
else
return null;
}
Then I could use this on reference types (e.g., object, string) as well as nullable value types (e.g., int?, double?): anything that can be assigned to null. But this isn’t possible.
Then again, for all I know, maybe it is? I know there’a no null constraint like I just fantasized about; but is there some workaround or clever way of accomplishing this that just hasn’t occurred to me?
I used to never use output parameters, partly I think the syntax just felt clumsy. However, a few years ago I started using them more and they’ve become a common aspect of the code that I write.
I think this is the kind of function where I would really consider writing the function with an output parameter and a boolean return type, as shown below:
With this approach there is no need to restrict your generic parameter to reference type or a nullable type.
As I mentioned above, I originally felt that output parameter syntax was clumsy, but after I really started using it frequently I felt that the code that consumed my functions with output parameters was actually more accurate towards representing the problem that I was trying to solve, if that makes any sense.