I want to be able to write
MyObject.IsNull(p => p.MyObjectProperty)
I think it is achievable with expression. I thied to implement it this way:
public static void IsNull<T>(this T root, Expression<Func<T, object>> expression)
{
if (CheckIfNull<T>(expression))
{
throw new ArgumentNullException(GetName(expression));
}
}
private static string GetName<T>(Expression<Func<T, object>> expression)
{
return ((MemberExpression)expression.Body).Member.Name;
}
public static bool CheckIfNull<T>(Expression<Func<T, object>> expression)
{
Expression<Func<T, object>> obj = o => expression.Compile().Invoke(o);
return obj == null;
}
But it is seams to be not working. How can I fix that?
objwithnull- which it never is, since one line above you are assigning a lambda-function to it. Instread checkobj(root) == null. Other than that, none of your functions ever returntrueorfalseand they should not compile. Please check the code you providedMyObject.IsNull(p => p.MyObjectProperty)should be. It looks like you want an exception to be thrown ifMyObjectPropertyit isnull, but then there is also theboolreturn value which is not ever used.boolwithvoid. Yes I want exception to be thorown in caseCheckIfNull<T>(expression) == true