Thorin Oakenshield
Thorin Oakenshield

Reputation: 14682

C#: Memory allocation for Anonymous Variables

I'm having a doubt regarding the memmory allocation for anonymous type variable.

if i declare a variable int Vaiable_Name it will allocate 4 bytes

but in case of Anonymous types , what will happen , and when the memory will get deallocated ?

Need we deallocate that manually??

for example

List<String> MyList=new List<String>{"0","1","0"}.Where(X=>X!="1").ToList();

Here how much bytes will be allocated for X?

Upvotes: 4

Views: 1275

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1501153

You haven't actually shown any anonymous types. You've shown a lambda expression. In this case, the compiler will effectively have created an extra method for you, like this:

private static bool SomeUnspeakableName(string X)
{
    return X != "1";
}

Then your code will be translated into this, effectively:

List<String> MyList=new List<String>{"0","1","0"}
       .Where(new Func<string, bool>(SomeUnspeakableName))
       .ToList();

... except actually, the compiler will create a single delegate instance in this case, and cache it. (And of course it will translate the uses of extension methods into normal calls to Enumerable.Where and Enumerable.ToList.)

So X ends up as a string parameter, effectively. At execution time, there's no such thing as a lambda expression (leaving expression trees aside). There's just a delegate created using the generated method.

Now if you were using anonymous types, like this:

var anon = new { Name = "Jon", Age = 34 };

then that would just create a new class, containing a string variable and an int variable, and with the same memory footprint as a normal class containing a string (which is a reference, of course) and an int.

Upvotes: 9

Darin Dimitrov
Darin Dimitrov

Reputation: 1038940

List<String> MyList = new List<String>{"0","1","0"}.Where(X=>X!="1").ToList();

This is not anonymous type. It is a collection initializer which creates a list containing 3 elements and then filters the initially created list.

Anonymous types would behave and consume the same memory as their non-anonymous type equivalent.

var foo = new 
{
    Prop1 = "value1",
    Prop2 = "value2"
};

would be the same as if we had a type:

class Foo 
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

...
var foo = new Foo 
{
    Prop1 = "value1",
    Prop2 = "value2"
};

Upvotes: 2

Related Questions