Angelo Charl Angelo Charl - 1 month ago 8
C# Question

C#: What is the default value of an uninstantiated object?

I have a quick question about default values in c#.

What us the default value of an object when not instantiated?

Here is an example:

public class Example
{
public Example() { Console.WriteLine("Content!"); }
}

public class MainClass
{
// obj = ???
Example obj;
}

Answer

The rule is simple

  • Local variables contain are not initialized at all, and thus contain trash.

A local variable is not automatically initialized and thus has no default value.

https://msdn.microsoft.com/en-us/library/aa691170(v=vs.71).aspx

  • Fields are initialized by their default values (zeros):

The initial value of a field, whether it be a static field or an instance field, is the default value

https://msdn.microsoft.com/en-us/library/aa645756(v=vs.71).aspx

For instance

 public class Example {
   bool m_Bool;       // default value == false
   int m_Int;         // default value == 0
   double m_Double;   // default value == 0.0
   string m_Text      // default value == null;
   Example m_Example; // default value == null;

   public void Test() {
     bool boolValue;     // contains trash, must be initialized before using
     int intValue;       // contains trash, must be initialized before using
     double doubleValue; // contains trash, must be initialized before using 
     string textValue;   // reference to trash, must be initialized before using   
     Example example;    // reference to trash, must be initialized before using   
     ...
   } 
 }