Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, 8 April 2014

C# Property by reference

I wanted to write a generic function to test a validation method of my object, but I wanted the function to be able to manipulate specific properties, like turning boolean values on or off.

Now one possibility is to pass the value by reference which is often something I don't like very much, but won't get into that too much right now, but since we are dealing with properties here the usual more elegant way is to create a wrapper or lambda function of some kind.

Now natrually before coding anything a quick google/SO search reveals some basic solutions and as one might expect involves some reflection as one CodeProject article here.

However I usually use dynamic reflection as a last resort as there is too much room for error here and referring to fields as strings just doesn't seem like the cleanest way. Also a super simple solution is by an SO post made here  (scroll down a bit) which simply just uses a small wrapper class you specifiy the getter and setter using 2 lambda expressions. This is certainly clean and simple, which I like, however I tried to create a function even simpler and more concise which also uses the compiler to ensure correctness, so I came up with this.

So much like the first version to use some reflection except no strings but using expressions. First extracting the property info from the expression, a nice clean wrapper object to help with this from this SO post:

public static class PropertyHelper<T>
 public static PropertyInfo GetProperty<TValue>(
  Expression<Func<T, TValue>> selector)
  {
  Expression body = selector;
  if (body is LambdaExpression)
  {
   body = ((LambdaExpression)body).Body;
  }
  
  switch (body.NodeType)
  {
   case ExpressionType.MemberAccess:
    return (PropertyInfo)((MemberExpression)body).Member;
    break;
   default:
    throw new InvalidOperationException();
  }
  }
}

So taking that a little further, creating a helper class to generate a lambda getter and setter

public static class PropertyHelper
{
 public static Func<TValue> GetPropertyGetter<T, TValue>(T value, Expression<Func<T, TValue>> selector)
 {
  var propInfo = (PropertyInfo)((MemberExpression)(selector).Body).Member;
  return () => (TValue)propInfo.GetValue(value, null);
 }

 public static Action<TValue> GetPropertySetter<T, TValue>(T value, Expression<Func<T, TValue>> selector)
 {
  var propInfo = (PropertyInfo)((MemberExpression)(selector).Body).Member;
  return v => propInfo.SetValue(value, v, null);
 }
}

Small note: This requires you to use a lambda expression for the property any other expression will break it, I didn't add all the checks to make it more terse. So Then the usage would simply be:
var getter = PropertyHelper.GetPropertyGetter(world, w => w.Hello);
var setter = PropertyHelper.GetPropertySetter(world, w => w.Hello);

And then you can get the property by calling:

getter();
setter("Hello");

Extending that a little further by adding a nice wrapper class:

public class PropertyWrapper<TValue> : IPropertyWrapper<TValue>
{
 protected PropertyInfo _propInfo;
 protected object _instance;

 public PropertyWrapper(PropertyInfo propinfo, object instance)
 {
  _instance = instance;
  _propInfo = propinfo;
 }

 public object Instance
 {
  get { return _instance; }
 }

 public TValue Value
 {
  get { return (TValue)_propInfo.GetValue(_instance, null); }

  set
  {
   _propInfo.SetValue(_instance, value, null);
  }
 }
}

Then you can pass around the wrappers:
var wrapper = PropertyHelper.GetPropertyWrapper(world, w => w.Hello)
Now you can easily use this in your generic method and manipulate any property:
  
private static void TestCondition(IPropertyWrapper condition)
{
 condition.Value = false;
 Console.WriteLine(condition.Instance.Validate());
 condition.Value = true;
 Console.WriteLine(condition.Instance.Validate());
}
Dynamic objects are of course another way to do this however you then still are missing out on the compile time checking, so I haven't coded out this solution, but I think I'd still rather use this approach then reflection by string name method. So there you have it, this seems like a nice clean way to create property references, you can take it one more step further by creating an object extension method for this, but I usually try to avoid this as it can clutter up the code completion just a little bit too much. But if you can think of an even better cleaner way in C#

Tuesday, 21 May 2013

AutoFac Dynamic Factories

AutoFac like many Ioc containers make it easy to declare your dependencies and just get them magically injected for you. The problem comes in when trying to control the lifetime of certain objects, especially if you are trying to create some shorter lifetime objects. Once you declare your dependency you don't have any more control over the lifetime of it. Also sometimes you might specifically need 2 different instances of an object. AutoFac just like many other containers has lifetime options when registering objects:
builder.RegisterType<TestClass1>().InstancePerDependency();
builder.RegisterType<TestClass2>().InstancePerLifetimeScope();
The first indicates that each dependency or call to the Resolve() method will give you a new instance. The 2nd indicates that each dependency or call to the Resolve() within the same lifetime scope will give you a new instance. This is sort of special as it actually shares the instance in the same call graph, lifetime scope or call to container.BeginLifetimeScope(). So this registration of specific to when sharing instances is preferred.

So even if you change all your objects to InstancePerDependency lifetime (which would be hugely limiting anyway) you still need a way to create these on-the-fly instances. The AutoFac solution is to resolve an object of type Owned<T>

However this means having the reference to the IContainer in your objects which is very bad and IOC 101 dont's. So just create a simple interface for your framework that you can use to inject abstract factories instead something like:

public interface IFactory<T>
{
    T Create();
}

This is very simple and easy to generate mocks for testing. You can also easily create a generic wrapper using lambda expressions to generate on the fly even when not using AutoFac or a different container. But for the autofac version, you can call it anything you like AutoFacFactory if you like, but it will function something like this:

public class Factory<T> : IFactory<T>
{
 private IContainer _container;

 public Factory(IContainer container)
 {
  _container = container;
 }

 public T Create()
 {
  var owned = _container.Resolve<Owned<T>>();
  return owned.Value;
 }
}
In order to get this to work there's a few simple steps to configure AutoFac:

First register the open generic type:

var builder = new ContainerBuilder();
builder.RegisterGeneric(typeof(Factory<>)).As(typeof(IFactory<>)).InstancePerDependency();

Next is that you have to actually register the container instance itself back to the container, as it seems its not automatic. This can actually be done easily but you need to construct a builder to update the container:

var postContainerBuilder = new ContainerBuilder();
postContainerBuilder.Register(c => container);
postContainerBuilder.Update(container);

Now you can declare dependencies to IFactory of any type that is registered and be able to create unique instances each time:

var builder = new ContainerBuilder();
builder.RegisterType<TestClass1>().InstancePerDependency();
builder.RegisterType<TestClass2>().InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(Factory<>)).As(typeof(IFactory<>)).InstancePerDependency();

var container = builder.Build();

var postContainerBuilder = new ContainerBuilder();
postContainerBuilder.Register(c => container);
postContainerBuilder.Update(container);

var factory1 = container.Resolve<IFactory<TestClass1>>();
var factory2 = container.Resolve<IFactory<TestClass2>>();

var t11 = factory1.Create();
var t12 = factory1.Create();

Assert.AreNotEqual(t11, t12);

var t21 = factory2.Create();
var t22 = factory2.Create();

Assert.AreNotEqual(t21, t22);

Tuesday, 6 November 2012

Singleton and Dependency Injection

Ayende wrote this great blog post on the Singleton pattern, I always enjoy these kinds of posts from him because he looks at them from a real world perspective. It reminded me to make a specific subtle point on Singleton and that is:
Most of the issues that people have with the Singleton aren’t with the notion of the single instance, but with the notion of a global static gateway, which means that it becomes very hard to modify for things like tests, and it is easy to create code that is very brittle in its dependencies on its environment.
This has often lead to statements about statics/singletons are evil. But they don't have to be. You should continue to create objects that utilize dependency injection and abstractions and make sure they are decoupled from such statics or instances. The way you do this is very simple: Here is some typical Singleton (Implementations may vary): So when using this you have a choice, you can either use it this way: The above usage is very hard to test and doesn't allow me to change the implementation of the GetRaise method. Another big problem is the Dishonest API, there is no indication when I create the object or call the method that there is a hidden dependency to Manager which is a typical problem with using Singletons and statics like this. The solution is to rather ask for the instance and not let your class know about the singleton at all: Now I can test and change the implementation as I like, for example create a new derivative: If you don't like the manual approach, these days IoC containers are everywhere and the setup for example StructureMap is this easy: The above will just use the default Singleton instance to resolve. But you can also override it as follows: These techniques are indeed very basic but so often overlooked. The singletons are not evil when used correctly but must remain living in the root layer of your application where all the calls are made initially.

Thursday, 25 October 2012

Simple BDD - Take 2

A while back I wrote the post Simple BDD where the idea was to show how you can write a self documenting, human readable test in BDD style without the need of any fancy frameworks using fluent syntax. I was literally inundated by feedback from one person. The complaint was that it is weird to write statements such as:

Given
Given
When
When
When
Then
Then

The argument is that this doesn't really read like a story and just seems like I am stuttering.

So I would like to make a small modification to this to show 2 points.

The test name

The test name will really be something descriptive that is most logical:

GivenARectangleWithWidthOf10AndHeightOf10TheAreaShouldCalculate100

I am sure I don't have to add the virtual spaces to make it more readable at this point as you would get the idea. The wording here is completely logical.

Implementation

To actually write this implementation that satisfies the test I am going write a Shape and Calculator and throw in a Visitor just to make it more interesting.

Now to write the grammar in a little bit more like a human, I thought to simply add an And method. Here is the full test and test class implementation:

Note

I DO recommend that you do not use too many evaluations (Asserts/Then) in one test and to rather break them up. The fact that I have shown it is just an example of what the syntax can do. Also the grammar is not set in stone and the idea is to adapt it to what you prefer.

Sunday, 29 July 2012

Simple BDD

I have spoken before about how much I like the fluent-interface. I use it a lot expecially with object builders. I was looking at the Bddify framework. I have known about this style of testing and BDD for a while, but was really inspired about how Bddify write tests.

I realized that I could do this so easily with everyday tests as well without the need for any fancy frameworks etc. And just make my own tests easier to write and understand.

I was doing a very simple schedule for an import process and heeding the warning by Ayende about scheduling. I tried to consider the wise words and established that my requirement is very simple and to the point and most of these won't be a problem for me. With this in mind I wanted to make sure there are no bugs in the schedule logic so this is what I came up with. First I could express my requirements in the test:

The implementation of this is very simple and I have just done so directly in my test class. It's just about the grammar Given a set of inputs When certain conditions are met, Then we can expect a specific result.

  • Given - Construction of the objects I am testing.
  • When - Setting some criterea on the objects I have created.
  • Then - Run a method and (Act and Assert)

Obviously to have a good grammar you first need to understand a bit more about your domain and tests. And what you will be testing, so when starting I still write the first test or 2 using a few variables and seeing how the test logic fits together and create my grammar from there.

Bugs with these kinds of things could be a nightmare in a live environment. So this style of testing helps you build all of the scenarios that you can think of and make sure those work through the lifetime of the solution.

Saturday, 14 April 2012

Chain Of Responsibility: Why Can't Programmers Program?

According to CodingHorror he was battling to understand why:

Like me, the author is having trouble with the fact that 199 out of 200 applicants for every programming job can't write code at all. I repeat: they can't write any code whatsoever.

In order to make sure that the applicant could write code they would ask them to perform a simple task:

Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

Most good programmers should be able to write out on paper a program which does this in a under a couple of minutes.

But Apparently:

Want to know something scary? The majority of comp sci graduates can't. I've also seen self-proclaimed senior programmers take more than 10-15 minutes to write a solution.

So apparently a number of companies use this question to quickly eliminate those who can't write any code. When I first heard of this I was surprised and thought what is the catch.

Would the person asking this be expecting some really fancy implementation?

But what the person is really looking for is to write it so that it just works exactly as requested

You can look at this page or search for examples which are available in just about every language out there, but here is the C# code:

public void Main()
{
    for (int
i = 1; i <= 100; i++)
    {
        FizzBuzz(i);
    }
}


public void FizzBuzz(int
value)
{
    if
(value % 3 == 0 && value % 5 == 0)
    {
        Console.WriteLine("FizzBuzz"
);
    }
    else if
(value % 3 == 0)
    {
       Console.WriteLine("Fizz"
);
    }
    else if
(value % 5 == 0)
    {
       Console.WriteLine("Buzz"
);
    }
    else
    {
       Console
.WriteLine(value);
    }
}

Now you can certainly try and get more fancy about this and some have certainly done so, but I thought it would be valuable to be able to write this and then say what fundamental principle are you violating and how to solve it.

The Chain Of Responsibility

The above example can be thought of in a real world application with various conditions for each of the inputs and providing a different implementation for each. And in this case this is a violation of a fundamental principle called the Open/closed principle

And in the above implementation we might want to add a check for the number divisible by 10 and print out Bazz. This certainly means our function is not Closed for modifications as we would have to add another code block and modify the if-else logic.

One solution to this problem would be to create one strategy per implementation and use the Chain-of-responsibility pattern

First create a printer object for any ancestor in the chain:

public abstract class Printer
{
    private Printer
_Next;
    public Printer SetNext(Printer
next)
    {
       this
._Next = next;
       return
next;
    }

    protected abstract bool HandlePrint(int
value);

    public virtual bool Print(int
value)
    {
        if (!this
.HandlePrint(value))
        {
           if (this._Next != null
)
           {
              return this
._Next.Print(value);
           }
           return false
;
        }
        return true
;
    }
}

The abstract method HandlePrint gets a value and it is up to the strategy to decide whether it supports the given value and handles the request. It can either stop processing or let the processing continue further down the chain.

And then we would have an implementation for each of the printing strategies:

public class FizzBuzzPrinter : Printer
{
    protected override bool HandlePrint(int
value)
    {
       if
(value % 3 == 0 && value % 5 == 0)
       {
           Console.WriteLine("FizzBuzz"
);
           return true
;
        }
        return false
;
    }
}


public class FizzPrinter : Printer
{
    protected override bool HandlePrint(int
value)
    {
        if
(value % 3 == 0)
        {
            Console.WriteLine("Fizz"
);
            return true
;
        }
        return false
;
    }
}


public class BuzzPrinter : Printer
{
    protected override bool HandlePrint(int
value)
    {
       if
(value % 5 == 0)
       {
           Console.WriteLine("Buzz"
);
           return true
;
       }
       return false
;
    }
}

Also we can now very easily add the ability to check for 10 and print Bazz by registering a new handler.

public class BazzPrinter : Printer
{
    protected override bool HandlePrint(int
value)
    {
        if
(value % 10 == 0)
        {
            Console.WriteLine("Bazz"
);
            return true
;
        }
        return false
;
     }
}

Now our implementation of our printing engine can be closed to modifications:

public void Main()
{
    Printer printer = new FizzBuzzPrinter
();
        printer
          .SetNext(
new BazzPrinter
())
          .SetNext(
new FizzPrinter
())
          .SetNext(
new BuzzPrinter
());

// Add bazz printer

    for (int
i = 1; i <= 100; i++)
    {
        Console.Write(string.Format("{0}:"
, i));

        if
(!printer.Print(i))
        {
            Console
.WriteLine();
        }
     }
}

image

So there you have it the solution can and is simple initially provided you know what the potential violation is and problems that can be caused down the line. And once you made more than 2-3 modifications to it its time to think about refactoring it.

Live writer was harmed 5 times during the making of this post.

C# Lambda Expressions and Closures

 

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

So lambda's are the coolest things in the world right? I sure love them, however I have discovered one or two pitfalls when working with them that I wanted to share, when I was still fairly new to them I had occasionally discovered weird behaviour and at the time didn't know what was wrong. When I encountered them again I remembered and decided to take a closer look.

Behind the scenes

First let's just look at what a lambda actually looks like behind the scenes.

Consider this simple lambda function. I have a list of actions and for each action i specify a lambda function that prints the value in the enumeration.

var items = new[] { "Foo", "Bar" };
var actions = new List<Action>();
string[] array = items;
foreach (var item in
items)
{
actions.Add(() =>
Console
.WriteLine(item));
}


foreach (var action in
actions)
{
action();
}

This is really just syntactic sugar and not really the code that is generated by the compiler. Let's look at the code that is generated by the compiler for the lambda function:

using System;
using
System.Runtime.CompilerServices;
[System.Runtime.CompilerServices.CompilerGenerated]

private sealed class
<>c__DisplayClass11
{
public string
item;
public void
<ModifiedArrayClosureForeachTest>b__f()
{
System.
Console.WriteLine(this
.item);
}
}

As you can see it is just a class with a 1 or more fields representing the variables you capture and a method that is used at the pointer to the action.

The For-Each loop pitfall

I want to show you how using lambdas in For-Each loops or in fact anywhere where you use variables that are outside of the scope can cause problems, I won't call this a bug but rather a pitfall and the compiler will not give you a warning of this.

If I run the first code snippet I notice a weird result.

Because it is clear that we have an array with 2 items Foo and Bar. I was expecting to see:

image

But instead this is what I got

image

Lets look at the code that is generated for the first code snippet for the For-Each statement loop:

string[] items = new string[]
{
"Foo"
,
"Bar"
};
List<Action> actions = new List<Action
>();
LambdaTests.<>c__DisplayClass11 <>c__DisplayClass =
new LambdaTests.<>c__DisplayClass11();
string[] array = items;
for (int
i = 0; i < array.Length; i++)
{
<>c__DisplayClass.item = array[i];
actions.Add(
new Action
(<>c__DisplayClass.<ModifiedArrayClosureForeachTest>b__f));
}

foreach (Action action in
actions)
{
action();
}

Interestingly enough the C# compiler is being really clever and realizes that this is an array converted this to a for loop to increase performance.

However look more closely to the anonymous function creation. There is only one instance and it is created above and outside of the scope of the for loop and the same item variable is overwritten each time, resulting in only the last item in the enumeration being saved.

Lets do this same test on an actual list with an enumerator.

var items = new[] { "Foo", "Bar" }.ToList();

This time the C# compiler is using an enumerator. However again the creation of the anonymous class is created outside of the For-Each loop and the same value is overwritten each time.

using (List<string>.Enumerator enumerator = items.GetEnumerator())
{
LambdaTests.<>c__DisplayClass15 <>c__DisplayClass =
new
LambdaTests.<>c__DisplayClass15();
while
(enumerator.MoveNext())
{
<>c__DisplayClass.item = enumerator.Current;
actions.Add(
new Action
(<>c__DisplayClass.<ModifiedArrayClosureForeachListTest>b__13));
}
}

Preventing the For-Each pitfall

In both cases this can be solved by assigning a new variable inside the foreach scope.

foreach (var item in items)
{
var
newItemScope = item;
actions.Add(() =>
Console
.WriteLine(newItemScope));
}

image

This time the compiler generates the code that creates a new lambda class for each iteration.

for (int i = 0; i < array.Length; i++)
{
string
item = array[i];
LambdaTests.<>c__DisplayClass10 <>c__DisplayClass =
new
LambdaTests.<>c__DisplayClass10();
<>c__DisplayClass.newItemScope = item;
actions.Add(
new Action
(<>c__DisplayClass.<ModifiedArrayClosureForeachTest>b__f));
}

Closures

Closures are the anonymous classes created for the lambda functions, that contains the methods and variables being referenced.

In the next seemingly harmless code snippet I create 3 actions independent of each other, but notice how i make a modification to sC. Because these are completely different scopes i would expect sC the last action not to be affected by changing the variable sC in a different closure, but it does.

string sA = "A";
string sB = "B";
string sC = "C";
Action
a = () =>
{
Console
.WriteLine(sA);
sC =
"D"
;
};


Action
b = () =>
{
Console
.WriteLine(sB);
};


Action
c = () =>
{
Console
.WriteLine(sC);
};

a();
b();
c();

The output:

image

The first lambda is modifying sC which is reflected in lambda c.

How is C# doing this?

Well because all the lambdas are accessing the variables on the same scope there is actually just one closure class with a method for each lambda and they all share the same fields:

LambdaTests.<>c__DisplayClass23 <>c__DisplayClass = new LambdaTests.<>c__DisplayClass23();
<>c__DisplayClass.sA =
"A"
;
<>c__DisplayClass.sB =
"B"
;
<>c__DisplayClass.sC =
"C";

Action a = new Action(<>c__DisplayClass.<LambdaInstancingTestsSameScope>b__20);
Action b = new Action(<>c__DisplayClass.<LambdaInstancingTestsSameScope>b__21);
Action c = new Action
(<>c__DisplayClass.<LambdaInstancingTestsSameScope>b__22);
a();
b();
c();

Lets restructure the scope and variables

I will move action a into its own scope and declare a local variable localSc and set the value.

string sA = "A";
string sB = "B";
string sC = "C";

var actions = new List<Action
>();

{
string localSc = "C"
;

Action
a = () =>
{
Console
.WriteLine(localSc);
localSc =
"D"
;
sC =
"D"
;
};
actions.Add(a);
}



Action
b = () =>
{
Console
.WriteLine(sB);
};
actions.Add(b);



Action
c = () =>
{
Console.WriteLine("c: "
+ sC);
};
actions.Add(c);



foreach (var action in
actions)
{
action();
}

sC is still being modified

image

However if we look at the code generated by the compiler there is a brand new class for action a (DisplayClass27)

LambdaTests.<>c__DisplayClass25 <>c__DisplayClass = new LambdaTests.<>c__DisplayClass25();
<>c__DisplayClass.sB =
"B"
;
<>c__DisplayClass.sC =
"C";
List<Action> actions = new List<Action
>();
LambdaTests.<>c__DisplayClass27 <>c__DisplayClass2 =
new
LambdaTests.<>c__DisplayClass27();
<>c__DisplayClass2.CS$<>8__locals26 = <>c__DisplayClass;
<>c__DisplayClass2.localSc =
"C";
Action a = new Action
(<>c__DisplayClass2.<LambdaInstancingTestsDiffScope>b__22);
actions.Add(a);

Action b = new Action
(<>c__DisplayClass.<LambdaInstancingTestsDiffScope>b__23);
actions.Add(b);

Action c = new Action
(<>c__DisplayClass.<LambdaInstancingTestsDiffScope>b__24);
actions.Add(c);

foreach (Action action in
actions)
{
action();
}

Now because localSc, it is in a new scope and does not exist in the main method scope it gets a new class of its own containing the field localSc, but interestingly notice the variable 8__locals26 we need to look at the class generated by the compiler to see the definition of locals26:

[System.Runtime.CompilerServices.CompilerGenerated]
private sealed class
<>c__DisplayClass27
{
public
LambdaTests.<>c__DisplayClass25 CS$<>8__locals26;
public string
localSc;
public void
<LambdaInstancingTestsDiffScope>b__22()
{
System.Console.WriteLine(
this
.localSc);
this.localSc = "D"
;
this.CS$<>8__locals26.sC = "D"
;
}
}

See that it is a pointer to the other closure and that i am still able to modify its variables through this pointer.

LINQ

So at this point you might be thinking:

This is all very interesting but why do I care if I use LINQ only.

Because Linq uses lambda expressions too so the same thing could happen:

var items = new[] { "Foo", "Bar" };
var actions = new List<Action>();

var itemsQuery = items.AsQueryable();

foreach (var item in
items)
{
if (item == "Foo"
)
{
itemsQuery = itemsQuery.Where(queryItem => queryItem == item);
}
}


foreach (var item in
itemsQuery)
{
Console
.WriteLine(item);
}

The same issue can be seen.

image

So also in fact anywhere you access a variable outside of the local scope could result in a modified closure.

More on variables and scope

So we found that the variables between these lambdas are shared, but what about the method? The strings are obviously value types to modifying the different variables will not cause the same modification in the variables of the main method.

I wanted to know too so I modified one of the code samples slightly and the results are very interesting.

string sA = "A";
string sB = "B";
string sC = "C";
string sD = "D";
Action
a = () =>
{
Console
.WriteLine(sA);
Console
.WriteLine(sC);
sC =
"D"
;
};


Action
b = () =>
{
Console
.WriteLine(sB);
};


Action
c = () =>
{
Console
.WriteLine(sC);
};

sC =
"X"
;
a();
b();
c();


Console.WriteLine(sC);
Console
.WriteLine(sD);

Notice that I declare the lambdas, then I modify sC after this point, I then run

Action a, b, and then c, finally in the main method I print out sC and sD, and I got these results:

image

So we saw previously that a new class is created for the anonymous (lambda) function and all the fields are set from the local variables, so the fact that the lambdas share the same value is of no surprise.

But how it is that I can still read and write to the same variables as the lambda functions?

NOTE: sD has a value of "D" and is never used in one of the lambda functions.

A look at the compiler generated code reveals the answer:

LambdaTests.<>c__DisplayClass23 <>c__DisplayClass = new LambdaTests.<>c__DisplayClass23();
<>c__DisplayClass.sA =
"A"
;
<>c__DisplayClass.sB =
"B"
;
<>c__DisplayClass.sC =
"C";
string sD = "D";

Action a = new Action(<>c__DisplayClass.<LambdaInstancingTestsSameScope>b__20);
Action b = new Action(<>c__DisplayClass.<LambdaInstancingTestsSameScope>b__21);
Action c = new Action
(<>c__DisplayClass.<LambdaInstancingTestsSameScope>b__22);
<>c__DisplayClass.sC =
"X"
;
a();
b();
c();

Console.WriteLine(<>c__DisplayClass.sC);
Console.WriteLine(sD);

Notice that there are no longer variables sA, sB, and sC by themselves and they are now replaced by one local variable that is the class generated for the lambda function. So the value is shared through the anonymous class instance. Then also NOTE that sD is still kept as a normal variable because it is never used in one of the lambda functions.

This has been some of my findings with lambda functions and closures, got any interesting findings of your own?