In C# structs are value types, but I am able to new
them as if they are reference types. Why is this?

- 4,503
- 3
- 38
- 76

- 45,256
- 81
- 201
- 304
-
2A constructor is really just a method that gets the special privilege of messing with an object before it is considered initialized. – Tory Mar 23 '13 at 18:29
5 Answers
Because they have constructors.
The new
operator doesn't mean "this is a reference type"; it means "this type has a constructor". When you new
something you create an instance, and in doing so you invoke a constructor.
For that matter, all value and reference types have constructors (at the very least a default constructor taking no args if the type itself doesn't define any).

- 700,868
- 160
- 1,392
- 1,356
-
Thanks. For Java, is "all value and reference types have constructors" also true? – Oct 30 '17 at 20:59
-
@Ben: I understand that Java primitive types do also have constructors. – BoltClock Oct 31 '17 at 01:34
-
Thanks. But why in https://stackoverflow.com/a/47024170 `new` can't apply to `int`. – Oct 31 '17 at 01:54
-
-
new
operator doesn't mean that it can be used only for reference types. It can be used with value types also.
From new Operator
Used to create objects and invoke constructors.
Since every value type implicitly has a public default constructor, all value types has default values. You can read Default Values Table.
For example;
int i = new int(); // i will be 0 for because its default values.
Default value for struct type;
The value produced by setting all value-type fields to their default values and all reference-type fields to null.
Also From 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.

- 97,193
- 102
- 206
- 364
You can "new" an integer as well.
The difference is you CANT pass a reference class by value.

- 48,127
- 24
- 147
- 185
It says right here in the MSDN document, the new
operator is used to invoke the default constructor of a value type.
You don't have to use the new operator to create a struct. If you do it will call its constructor, if you don't all field will remain unassigned.

- 1,840
- 26
- 48