I'm writing a very simple extension method that attempts to cast objects from one type to another. The intent of having this method is very similar to Int32.TryParse(string, out int)
, which allows the user to see 1) if the conversion succeeded, and 2) what the converted object is, all in one line.
Because this method will deal exclusively with class objects, it's possible that the object to be cast is actually null. Null can be cast to any nullable type (at least that's what it looks like based on my testing), so technically the method would always succeed in that situation. On the other hand, trying to convert null doesn't serve a lot of purpose and is usually a sign of things gone wrong. Therefore, my question is: in the case of the supplied object being null, should I return true (the cast succeeded) or false (did not succeed)?
This is (more or less) the method in question:
public static bool TryGetAs<T>(this object obj, out T output) where T : class
{
output = null;
if (obj == null)
return [true or false];
output = obj as T;
return output != null;
}
in the case of the supplied object being null, should I return true (the cast succeeded) or false (did not succeed)?
-- Did the cast actually succeed or not?null
to another type? Plenty of the casts I make are on potentiallynull
values.null
object. It will not NRE.someVariable.SomeExtensionMethod();
is transformated by the compiler into the morale equavalent ofClassExtensionMethodIsIn.SomeExtensionMethod(someVariable);
, which obviously is never going to NRE.