2

I have this (in a C# MVC project):

public class Bindable<TEntity> 
{
    //(...)
    public IHtmlString FormControlTextField<T>(string id, Expression<Func<TEntity, T>> member)
    {
        var prop = (member as MemberExpression).Member;
        var strLen = prop.GetCustomAttributes(typeof(StringLengthAttribute), false).OfType<StringLengthAttribute>().FirstOrDefault();
        //(...)
    }
//(...)
}

and for some weird reason to me, it is throwing a NullReferenceException on the method's second line, since it's returning null from the cast on the first line.

The method is being called like this (from a View):

@empresa.FormControlTextField(p => p.CNPJ, Model.CNPJ) 

@* "empresa" is an instance of Bindable<EmpresaCliente> *@
@* "CNPJ" is a property in EmpresaCliente *@

What is wrong with this? Or, is there a workaround to test "p.CNPJ" for custom attributes?

Marcelo Myara
  • 2,841
  • 2
  • 27
  • 36
  • 3
    I think you probably want to use `member.Body as MemberExpression` here. – DavidG Oct 27 '18 at 16:56
  • @DavidG, you're right. My bad... Do you want to post it as the answer so I can mark it as the right one? – Marcelo Myara Oct 27 '18 at 17:16
  • @HimBromBeere Too hasty with that CV I think, OP already knows why the NRE is happening. – DavidG Oct 27 '18 at 17:24
  • @HimBromBeere, as you please. But the point on my question is not knowing whar a null exception is (this, of course, has to be clear for someaone using generics and delegates). It's all about why it's happening when casting an expression into a MemberExpression class. (as correctly answered by DavidG). – Marcelo Myara Oct 27 '18 at 17:35
  • Since @HimBromBeere isn't responding, I'm going to reopen this question and provide an answer. Not usually something I'm comfortable doing but I'm not satisified this should have been closed in the first place. – DavidG Oct 27 '18 at 17:44

1 Answers1

2

The problem is that Expression<Func<TEntity, T>> isn't a MemberExpression, it's a LamdaExpression, that's why the cast fails. What you really want to do is cast member.Body instead. As an aside, you should use a direct cast in your code:

var prop = ((MemberExpression)member.Body).Member;

Or even better, do a check:

var expression = member.Body as MemberExpression;
if(expression == null)
{
    throw new ArgumentException("Bad expression passed in!");
}
var prop = expression.Member;
DavidG
  • 113,891
  • 12
  • 217
  • 223