Geeks With Blogs
David Redding Blog? What blog? Theres no blog to see here. Please move along

clip_image001[7]

    So, how often do you get to sit around  with your penis thinking about how you can use it to write less code?  Apparently the guys over at MS were when they introduced Lambda expressions and the penis operator "=>" to C# 3.0.  At any rate, what follows is my take on a bit of history leading up to promiscuous use of "=>".

    Ok, let me back up a little bit.  Lambda expressions are essentially just Functions.  They are common in functional programming languages like Lisp, F# and ML.  They are also a new addition to C# 3.0.  Granted, they are (for the most part) syntactical sugar.  And you'll typically only use them in places you would use any other type of anonymous delegate (were going to ignore LINQ with it's fancy-ass expression trees for the purposes of this tech in 5 min).

    Your typical lambda expression in C# is going to look like this:

e=>e%2==0

Now, if your like me, and you've been used to your typical empirical syntax this looks like Greek (coincidentally , the lambda is of Greek origin).  The expression above, in C# is the same as writing this method:

bool SomeFunctionName(int e) 
{ 
   //the % is the modulus operator which just divides the two numbers 
   //and returns only the remainder 
   return e%2==0; 
}

Or this, in this way as an Anonymous method

public static void Main(string[] Args) 
{ 
    MyObject o = new MyObject(); 
    Console.WriteLine(o.MethodThattakesADelegate ( delegate (int e) { return e%2==0; } ) 
}

as you can see, it just returns wether or not the passed in number is even.

    Ok, enough with this, lets get back to this Penis operator thing.  Like I said, the lambda expression looks totally different than your typical anonymous method or standard method.  For one it has the Penis operator '=>' (if anyone tells you it has a different name, that's the name their wife gave theirs).  Now, in traditional Tech in 5 min fashion, I will demonstrate how this new fancy sugar can be used to explain another piece of life with your code.oldmarriedcouple

    the way I see it, there are only 3 forms of whoopie in the world (technically there are 4, but ageing comedians on "the view" don't count here).  Low and behold, it only took a few iterations, but C# can now actually describe each. 

1.) C#1.1 overly talkative with "Feelings". 
    The way it used to be with C# was that you had to be married to make whoopie work. Those Married people, or those in a long term relationship have well defined variables and methods of operation and they are generally visible for the rest of the world to see (unless you subclass NookieOnTheSide
For instance...

public class DontLetMyEmployeerSeeThisBlogPost 
{  
    public delegate bool MakeWhoopie(Position p);  
    public bool BoringOldPeopleSexin(Position P)  
    {  
        If(p.Name != "Missionary")  
        throw new Exception("Positions other than Missionary are only allowed in the NookieOnTheSide object");  
        If(DidTheViagraWork(p))  
            return true;  
        else  
            return false;  
    } 
    
    private bool GetItOn(MakeWhoopie FinallyGettinSome, int Endurance) 
    { 
        if(Endurance > 0) 
        { 
            FinallyGettinSome(new Missionary_Position()); 
        } 
    }

    public static void Main(string[] Args) 
    { 
        DontLetMyEmployeerSeeThisBlogPost AtMyPlace = new DontLetMyEmployeerSeeThisBlogPost(); 
        AtMyPlace.GetItOn(BoringOldPeopleSexin,1); 
    }

}

 

As you can see, this kind of .Net 1.1 lovin' is ... well boring,overly verbose and does not look spontaneous at all.  You'd swear that was VB. 

2.)The C# 2.0 heyday. The world hasn't seen free love like this since Madonna was in high school.  Jimi Hendrix would be proud.

In 2.0 we gained the ability to use Anonymous methods.  This gave us Closures and a better opportunity to shoot ourselves in the foot, but none the less, it was a great addition to have.  What makes Anonymous methods really interesting is that they gave us access, within the delegate, to variables declared within the same scope of the method their hosted in, and not just variables it creates and defines. In addition, we don't care about the method name, we only care about what It can do for us....enter one night flings. 

What we create still has to conform to the delegate we made, so we still need a delegate defined somewhere.  So, for our hippies, we create this method in our Main...

AtMyPlace.GetItOn(delegate(Position p){return PeaceAndLoveManEspeciallyLove(p);},10);

And of course we have to add the method were callingflowerpower

public bool PeaceAndLoveManEspeciallyLove(Position p,int numberOfShrooms) 
{ 
    If(numberOfShrooms > GetDude().strangeOdor) 
        return true; 

    return false; 
} 

Ok, so this is a slight improvement on the amount of code we have to write.  And were pretty blatent about both the implementation and intent of the method call.  This works great for smaller bits of delegate shuffling.  I generally stick to the philosophy that if my anonymous delegate goes beyond 3 functional statements or 40 characters (+/-) AND closure isn't a consideration, i'll switch back to using the married style.  Cause lets face it, if you've got that much effort going into "Free" love, then you must be married.

3.)Contemporary C# 3.0, Gettin' on it like $5 beer bucket nights at the local dive.

Now, with 3.0, we have several opportunities in the new Lambdas.  Unlike the last two methods where we had to romance the delegate a little bit with either a direct call to a method or a bouquet of a keyword and parameter signature.  Now do we really need to know all this stuff in a modern "Smack' dat" age?  Hell No,  Lambda expressions are the the equivalent of saying "I don't care what your name is or what you call the crap you take.  What's important is I've got what your function needs and I'm going to point my penis at you to give it."  So the shortened version of our anonymous delegate becomes something like this...

AtMyPlace.GetItON(p=>TapDatAss(p),5);

This, of course, assumes that we can TapDatAss (we do still have to write methods that we intend on calling).  This is thanks to the penis operator, here is a simple diagram that describes the way it works:

LambdaExpression

An interesting note here is that in our example, we KNOW that the delegate required by TapDatAss Returns a Boolean, and accepts a Position as a parameter.  The compiler knows this too, so we don't HAVE to explicitly type that out.  The code finally knows "What we mean".

And if you've got more than one thing to dish out to your delegate(you lucky bastard!) it's this simple, just stick it in parenthesis and comma delimit it.

(a,b)=>a+b

Also, if you need to explictly return a value, like in the following example, you use the moustache (curly brace for those of you not living in dave world).

(a,b)=>{return (int)a+b;}

As a special note.  If your using Visual studio 2008 on a .net 2.0 app (evaluating it or whatever) or your using the 3.0 integration for 2005 you can use Lambda expressions.  While they are not native to the 2.0 framework, they do compile down to IL Code that can be understood.  Meaning that you get support for them from the 3.0 libraries, but they are compliant at an IL level with the 2.0 runtime.  Viva la C# 2.5!

Now, if your like me, you see a lambda and forget the syntax of how to use them. Just remember, it's a more compact version of the verbose Anonymous Delegate syntax.  The best thing to keep in mind is this saying "I'm going to give the stuff on the left side of the penis to the right side, and the right side returns the favor."  And since we live in a liberal society we only want to "Infer" that were giving a position to TapDatAss using the penis operator, not say it direct.  Cause if we did that we might offend someone.  And far be it for me to inspire more work for HR.

 

Most important.... Come to AADND!!!

Posted on Tuesday, December 11, 2007 9:45 PM Five Min Tech | Back to top

Copyright © Dave Redding | Powered by: GeeksWithBlogs.net