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?
From
struct (C# Reference)on MSDN: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.
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).