#782 – You Can Create an Instance of a struct Without the new Keyword
February 18, 2013 1 Comment
Like a class, you can create an instance of a struct using the new keyword. You can either invoke the default parameterless constructor, which initializes all fields in the struct to their default values, or you can invoke a custom constructor.
// Method 1 - Parameterless constructor, data in struct initialized to default values DogCollar collar = new DogCollar(); // Method 2 - Call custom constructor DogCollar collar2 = new DogCollar(10.0, 0.5);
In either case, a constructor is called.
You can also create an instance of a struct by just declaring it, without using the new operator. The object is created, although you can’t use it until you’ve explicitly initialized all of its data members.
// Method 3 - Just declare it DogCollar collar3; // Error - Can't use collar3 yet (use of unassigned field) Console.WriteLine(collar3.Length);
We need to first initialize all data members:
// Correct - initialize first DogCollar collar3; collar3.Length = 10.0; collar3.Width = 5.0; Console.WriteLine(collar3.Length);