0

Saw the code here. Can any one tell me what it means?

    Action wrappedAction = () => 
    { 
        threadToKill = Thread.CurrentThread; 
        action(); 
    }; 

Can we write such code with .net v2.0...?

Community
  • 1
  • 1
deostroll
  • 11,661
  • 21
  • 90
  • 161
  • Just a note ... this would be C# 3.0 syntax, which would require .NET 3.5, however, recall C# 3.0 came with .NET 3.5 and that .NET 3.5 is actually just additional libraries that is still built on CLR v2.0. – Richard Anthony Hein Nov 16 '09 at 17:57
  • FWIW, C# 3.0 syntax requires at least .NET 2.0 framework. The project settings determine if it's compiled for 2.0 or 3.5 framework. – spoulson Nov 16 '09 at 17:58

2 Answers2

5

It means that wrapAction is a delegate, that takes in no parameter and that executes the following code block

  threadToKill = Thread.CurrentThread; 
  action();

It's equivalent to

public delegate void wrapActionDel(); 

public void wrapAction()
{
      threadToKill = Thread.CurrentThread; 
      action();
}

public void CallwrapAction()
{
   wrapActionDel del = wrapAction;
   del ();
}

You can see that this is verbose, but Action is not.

And, this is only available in .Net 3.5. Don't worry, your .net 2.0 code will work seamlessly with .net 3.5, so you can just upgrade.

Graviton
  • 81,782
  • 146
  • 424
  • 602
  • +1, re upgrading, it's amazing how many people don't think like this. – Mark Dickinson Nov 16 '09 at 15:16
  • 1
    @Mark: Re upgrading: Remember that "getting the code to run" is only part of the upgrade process. Other parts are: Updating the deployment process (newer framework), updating the system requirements (W2k no longer supported), updating the dev environment (VS 2005 -> 2008), etc. – Heinzi Nov 16 '09 at 15:22
  • why are you += a delegate, it is not an event. you would want to "new" the delegate – CSharpAtl Nov 16 '09 at 15:23
  • @CSharpAtl, both are OK. You can install Resharper and it will suggest the method I put forward. – Graviton Nov 16 '09 at 15:27
  • You can do `wrapActionDel del = wrapAction;` but not `+=` and then call it as `del();` – CSharpAtl Nov 16 '09 at 15:36
  • @Heinzi - you should want to upgrade (should have already upgraded?) the development environment to 2008 for any number of reasons - not least multi-targetting - regardless of whether you are able to bring the projects up to V3.5 – Murph Nov 16 '09 at 15:41
2

That is a lambda expression, and is only available in C# 3.0+. The C# 2.0 version of that code looks like this:

Action wrappedAction = delegate() 
{ 
    threadToKill = Thread.CurrentThread; 
    action(); 
};

Assuming you have declared the Action delegate previously.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • This is syntactic sugar, not framework magic. So, should read "...only available in C# 3.0+. The C# 2.0 version..." – spoulson Nov 16 '09 at 18:00