2

I wonder to know how the .Net Framework handles the declared but not instantiated object situation.

For example i declare an object like

DropDownList ddl;

and do nothing about it. I know that i should do something with this variable and get a warning about it, but what i don't know is the where it will be stored.

Is there a lookup table that stores the data of all declared variables? Or is there a virtual reference for every declaration?

Edit : I just wanted to know how the memory allocated for this object declaration.

Edit2 : Whether it's a local variable or not, i'm just talking about the memory allocation structure. I wonder to know where this references stored.

4

5 回答 5

6

If ddl is a field, then the value of ddl will be null, as it is a reference type.

Any attempt to call a member on it will result in a NullReferenceException.

If it is a local variable it will simply be unassigned.

Value types will get the default(T) of their type.

The compiler itself may remove the call completely, depending on where it was declared, but this is an implementation detail.

于 2013-02-22T13:10:56.167 回答
1

If you are talking about a local variable then the compiler can simply optimize it out of existence since noone can be using it (if you attempted to use it without initializing the compiler would have protested with an error). In fact the .NET 4 compiler did this for me when I tested just moments ago.

If you are talking about a field in a class then it is initialized with the default value for its type as part of the object construction.

于 2013-02-22T13:11:17.447 回答
1

From your description, it sounds like you're talking about a local variable. When you declare a local variable in usual implementations and without any optimizations, then space is reserved for it on the stack (most probably), with a null reference as its value.

You could look into the StackFrame class if you want to inspect further (I've never used it).

于 2013-02-22T13:12:52.293 回答
1

The variable is stored in your assembly. It will always have it's default value null.

In release mode (compiler is set to optimize) it's optimized and it is not stored anywhere.

If you want to know more about IL and how the compiler works, wikipedia has a good article to start.

于 2013-02-22T13:16:14.403 回答
1

All variables are stored into a class or method. Variables declared into a class can be listed using .NET Reflection :

class Class1 { private int i; public string s; }
typeof(Class1).GetFields(BindingFlags.Instance); // returns all instance fields
typeof(Class1).GetFields(); // returns all instance public fields
typeof(Class1).GetProperties(); // returns all instance public properties

Variables declared into a method cannot be inspected with .NET Reflection mechanisms.

于 2013-02-22T13:16:41.557 回答