Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 511
Thorin Oakenshield Avatar asked Dec 21 '22 23:12

Thorin Oakenshield


1 Answers

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.

like image 159
Jon Skeet Avatar answered Dec 28 '22 09:12

Jon Skeet