So, I really enjoy using extension methods.. maybe a bit too much. So, I’m going to ask about my latest enjoyment to ensure that I’m not going too far.
Scenario is that we have a Guid? variable that gets passed in. If the variable is null or Guid.Empty, then we want to use a different Guid. So, I wrote an extension method to make it read like English:
internal static Guid OrIfEmpty(this Guid? guid, Guid other)
{
if (!guid.HasValue || guid.Value == Guid.Empty)
{
return other;
}
return guid.Value;
}
This automatically implies that a “null this” will not throw an exception. For instance, this will work:
((Guid?)null).OrIfEmpty(other);
This is not possible without using extension methods, and in my opinion can be quite misleading. However, it’s just so concise and clean! So, what do you think? Is this an acceptable thing to do or could it be too confusing to other programmers?
Also, I’m sure there will be other scenarios where I do things like this and checking this for null, but this is the best example I have right now.
Note: I’m not really asking about this Guid? business in particular. I’m asking more about the overall pattern implemented (having an extension method where the this can be null)
Sure it is, just make is a regular static method call (which is all extension methods are):
I agree, since it looks like you’re calling an instance method on a
nullinstance. It could be worse:At first glance this looks like an obvious
NullReferenceExceptionwaiting to happen, but it compiles and works as designed.Since your question is really just soliciting opinions, there’s not one right answer, but I certainly would be cautious and document the extension method to indicate that the
thisparameter could benull. Or (as @quezalcoatl implies) rename it to be more explicit that it supportsnullvalues: