I was getting a NullReferenceException in a web application and spent a huge deal of time to actually find the problem. I reproduced the problem with a console application. You can try to run the following code as it is –
using System;
using System.Linq.Expressions;
namespace Expression
{
public struct ValueType { }
public class ReferenceType { }
public class MyClass
{
public ReferenceType ReferenceType { get; set; }
public ValueType ValueType { get; set; }
}
class Program
{
public static string GetPropertyName<T>(Expression<Func<T, object>> expression)
{
return (expression.Body as MemberExpression).Member.Name;
}
static void Main(string[] args)
{
MyClass c1 = new MyClass();
MyClass c2 = new MyClass();
Console.WriteLine(GetPropertyName<MyClass>(x => x.ReferenceType));
// No Error
Console.WriteLine(GetPropertyName<MyClass>(x => x.ValueType));
// System.NullReferenceException
}
}
}
So the problem is the generic function GetPropertyName works when the expression given as the parameter of the function with the Reference Type property but The Value Type property causes System.NullReferenceException
at (expression.Body as MemberExpression).Member
.
So my question is why it works for reference type and not value type?