Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the keyword "new" do to a struct in C#?

Tags:

c#

object

struct

In C#, Structs are managed in terms of values, and objects are in reference. From my understanding, when creating an instance of a class, the keyword new causes C# to use the class information to make the instance, as in below:

class MyClass {     ... } MyClass mc = new MyClass(); 

For struct, you're not creating an object but simply set a variable to a value:

struct MyStruct {     public string name; } MyStruct ms; //MyStruct ms = new MyStruct();      ms.name = "donkey"; 

What I do not understand is if declare variables by MyStruct ms = new MyStruct(), what is the keyword new here is doing to the statement? . If struct cannot be an object, what is the new here instantiating?

like image 606
KMC Avatar asked Feb 09 '12 08:02

KMC


People also ask

Can we use new keyword for struct?

A struct object can be created with or without the new operator, same as primitive type variables. Above, an object of the Coordinate structure is created using the new keyword.

How do you define a new struct?

Create struct Variables When a struct type is declared, no storage or memory is allocated. To allocate memory of a given structure type and work with it, we need to create variables. Another way of creating a struct variable is: struct Person { // code } person1, person2, p[20];

How do you instantiate a struct without new?

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.

What is the use of struct keyword in C?

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).


1 Answers

From struct (C# Reference) on MSDN:

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.

To my understanding, you won't actually be able to use a struct properly without using new unless you make sure you initialise all the fields manually. If you use the new operator, then a properly-written constructor has the opportunity to do this for you.

Hope that clears it up. If you need clarification on this let me know.


Edit

There's quite a long comment thread, so I thought I'd add a bit more here. I think the best way to understand it is to give it a go. Make a console project in Visual Studio called "StructTest" and copy the following code into it.

using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace struct_test {     class Program     {         public struct Point         {             public int x, y;              public Point(int x)             {                 this.x = x;                 this.y = 5;             }              public Point(int x, int y)             {                 this.x = x;                 this.y = y;             }              // It will break with this constructor. If uncommenting this one             // comment out the other one with only one integer, otherwise it             // will fail because you are overloading with duplicate parameter             // types, rather than what I'm trying to demonstrate.             /*public Point(int y)             {                 this.y = y;             }*/         }          static void Main(string[] args)         {             // Declare an object:             Point myPoint;             //Point myPoint = new Point(10, 20);             //Point myPoint = new Point(15);             //Point myPoint = new Point();               // Initialize:             // Try not using any constructor but comment out one of these             // and see what happens. (It should fail when you compile it)             myPoint.x = 10;             myPoint.y = 20;              // Display results:             Console.WriteLine("My Point:");             Console.WriteLine("x = {0}, y = {1}", myPoint.x, myPoint.y);              Console.ReadKey(true);         }     } } 

Play around with it. Remove the constructors and see what happens. Try using a constructor that only initialises one variable(I've commented one out... it won't compile). Try with and without the new keyword(I've commented out some examples, uncomment them and give them a try).

like image 91
joshhendo Avatar answered Oct 02 '22 15:10

joshhendo