Kolichikov Kolichikov - 2 months ago 24
C# Question

Cannot perform runtime binding on a null reference on Nullable type

So I searched through the other NullReferenceException and runtime binding questions on SO, but couldn't find an answer to this one.

Basically, I have the code below. The method

ManipulateConcrete
returns False, as you would expect it to, but the method
Manipulate
throws


'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in
System.Core.dll

Additional information: Cannot perform runtime binding on a null
reference


Code:

class Program
{
static void Main(string[] args)
{
var myClassInstance = new MyClass() { MyGuid = null };

ManipulateConcrete(myClassInstance);
Manipulate(myClassInstance);
Console.ReadLine();
}

static void Manipulate(dynamic myClass)
{
Console.WriteLine(myClass.MyGuid.HasValue);
}

static void ManipulateConcrete(MyClass myClass)
{
Console.WriteLine(myClass.MyGuid.HasValue);
}

}

class MyClass
{
public Guid? MyGuid;
}


Am I missing something really obvious? Or is this a limitation of dynamic? If it's the latter, does anyone know the underlying reason for this?

Answer

When using dynamic, static types are not considered. So, inside Manipulate, the value of myClass.MyGuid is null, typed as dynamic. And dynamic does not know how to access any properties on a null instance, so it throws.

One way to fix this is to compare with null, instead of using .HasValue:

Console.WriteLine(myClass.MyGuid != null);

Another option would be to get rid of dynamic by casting to Guid?:

Guid? guid = myClass.MyGuid;

Console.WriteLine(guid.HasValue);