views:

84

answers:

2

The question is about the structs. When I declare a struct type variable/object (don't know which one suits better) or an array or list of structs, do I have to call the constructor explicitly like objects or just declaring will suffice like variables?

+12  A: 

Structs in C# can be created with or without invoking a constructor. In the case when no constructor is invoked, the members of the struct will be initialized to default values (essentially zeroed out), and the struct cannot be used until all of its fields are initialized.

From the documentation:

When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.

Below are some examples:

struct Bar
{ 
   public int Val;  

   public Bar( int v ) { Val = v; }
}

public void Foo()
{
    Bar z;      // this is legal...
    z.Val = 5;

    Bar q = new Bar(5); // so is this...
    q.Val = 10;

    // using object initialization syntax...
    Bar w = new Bar { Val = 42; }
}

Arrays of structs are different than a single struct variable. When you declare an array of a struct type you are declaring a reference variable - as such, you must allocate it using the new operator:

Bar[] myBars = new Bar[10];  // member structs are initialized to defaults

You can also choose to use array initialization syntax if your struct has a constructor:

Bar[] moreBars = new Bar[] { new Bar(1), new Bar(2) };

You can get more sophisticated than this. If your struct has an implicit conversion operator from a primitive type, you can initialize it like so:

struct Bar
{ 
   public int Val;  

   public Bar( int v ) { Val = v; }

   public static implicit operator Bar( int v )
   {
       return new Bar( v );
   }
}

// array of structs initialized using user-defined implicit converions...
Bar[] evenMoreBars = new Bar[] { 1, 2, 3, 4, 5 };
LBushkin
I'm embarrassed to say that I've developed in C# for two years and never once used or even came across the implicit keyword!
Pierreten
A: 

Struct is a Value Type in C#, so it uses Stack memory rather than Heap.

You can declare a struct variable in the regular way e.g int a = 90;,

int is a struct type in c#.

If you use new operator then the corresponding constructor will be invoked.

Indigo Praveen