Pass Property as Expression

I recently needed to pass a property of a class as an expression to a method and read value from it. I found the code that I finally ended up interesting and thought it might be useful to share it here.

void Main()
{
var instance = new Test();
instance.FName= "jia";
PrintMethod(x=>x.FName,instance);
}
public void PrintMethod(Expression<Func> action,dynamic instance)
{
var memberExpr = action.Body as MemberExpression;
var propInfo = memberExpr.Member as PropertyInfo;
var value = propInfo.GetValue(instance);
Console.WriteLine(value);
}

class Test
{
public string FName{get;set;}
public string LName{get;set;}
}

It might look I could have passed the value directly instead of as an expression, but the real life scenario was much complex than one demonstrated in the example.

Multicasting with Action

Func and Action are inherited from System.MulticastDelegate, which means that you could actually do multicasting with them and add multiple methods to the InvocationList. Let’s check how we do it.

Action Action1 = () => Console.WriteLine($"Hello From {nameof(Action1)}");
Action Action2 = () => Console.WriteLine($"Hello From {nameof(Action2)}");
Action Action3 = () => Console.WriteLine($"Hello From {nameof(Action3)}");
Action Action4 = () => Console.WriteLine($"Hello From {nameof(Action4)}");
Action Actions = Action1 + Action2 + Action3 + Action4;
Console.WriteLine($"Length of Invocation List :  {Actions.GetInvocationList().GetLength(0)}");
Actions();

Output of above code would be

Hello From Action1
Hello From Action2
Hello From Action3
Hello From Action4

The same can be done with Func as well. How do we remove one Action , same syntax as the delegates.

Actions -= Action4;

In fact, we could also use Actions instead of specifying delegates for events.

void Main()
{
  var demo = new DemoClass();
  demo.OutOfRange += ()=> Console.WriteLine("Out of Range");
  demo.NotAllowed += (x)=> Console.WriteLine($"Not Allowed : {x}");
  demo.Method1();
}
public class DemoClass
{
public event Action OutOfRange;
public event Action NotAllowed;
public void Method1()
{
       if(OutOfRange != null)
       OutOfRange();

       if(NotAllowed !=null)
       NotAllowed("Hey that's not allowed");
}
}
We could tweak it further by assigning a default action for our events. In this way, you can remove the checks for null. This is a possibility, but I am not quite sure if Microsoft Coding Conventions recommend Actions for events.