Sunday, April 22, 2012

Use Action instead of Func when you wish for a Func to return nothing.

Imagine if, in this scenario, one was to:

  1. make the private methods return void (warning: this is a silly example)
     
  2. replace these two lines:
    string thirdValue = mathDelegate(firstInteger, secondInteger);
    var result = new { calulation = thirdValue };

     
    with these two lines:
    mathDelegate(firstInteger, secondInteger);
    var result = new { calulation = "?"};

     
  3. replace this line:
    Func<Int32,Int32,string> mathDelegate;
     
    with:
    Func<Int32,Int32> mathDelegate;
     

 
 

It wouldn't work! You cannot compile this. C# 4.0 in a Nutshell has pointed out to me that the last parameter in the angle brackets of a Func is the expected return type! One must use Action in lieu of Func like so to get the desired effect:

Action<Int32,Int32> mathDelegate;

 
 

I find a lot of the nuisances that one must be obedient to in the name of shapeshifting in various ASP.NET circumstances to just be goofy, not intuitive, and impossible to guess at without the crutch of reference. Another example: The order and number of parameters that go into an ActionLink effect an ActionLink in really odd ways. Whatever.

No comments:

Post a Comment