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?
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 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With