Given a class with an implicit conversion operator to a Guid
:
class MyId
{
private readonly Guid innerGuid;
public MyId(Guid innerGuid)
{
this.innerGuid = innerGuid;
}
public static implicit operator Guid(MyId id)
{
return id.innerGuid;
}
}
When assigning to a Nullable<Guid>
:
static void Main(string[] args)
{
MyId someId = null;
Guid? optionalId = someId;
Console.WriteLine("optionalId = " + (optionalId.HasValue ? optionalId.Value.ToString() : "NULL"));
}
I would expect the null reference to simply propagate across from someId
to optionalId
. ie. get the console output:
optionalId = NULL
However the compiler seems to take precedence on the Nullable's inner Guid type, and it attempts to execute the implicit conversion, which throws a NRE as the id
parameter is obviously null.
Is this a bug or by design?
It can be fixed with a null coalescing operator and explicit null value:
static void Main(string[] args)
{
MyId someId = null;
Guid? optionalId = someId ?? (Guid?) null;
Console.WriteLine("optionalId = " + (optionalId.HasValue ? optionalId.Value.ToString() : "NULL"));
}
But that seems very weird. Resharper even fades it out, implying its unnecessary and states:
'??' right operand is always null
because you've a variable of type MyId, not of Guid? and you're assigning that variable to a Guid? and the MyId type has an IMPLICIT conversion operator. If you made it EXPLICIT then the compiler would probably complain about no conversion. What exactly would you expect to happen by assigning a null Foo class instance to a Guid? variable? Do you really expect that to be meaningful? –