Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a struct is a value type why can I new it? [duplicate]

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

like image 252
Sachin Kainth Avatar asked Mar 23 '13 17:03

Sachin Kainth


People also ask

Why is struct a value type?

While a struct is a value type, a class is a reference type. Value types hold their value in memory where they are declared, but reference types hold a reference to an object in memory. If you copy a struct, C# creates a new copy of the object and assigns the copy of the object to a separate struct instance.

Is a struct a value type or reference type?

Structs are value types, while classes are reference types, and the runtime deals with the two in different ways. When a value-type instance is created, a single space in memory is allocated to store the value. Primitive types such as int, float, bool and char are also value types, and work in the same way.

Can struct values be changed?

Unlike classes, a constant struct's properties cannot be changed—not from outside the struct, not even from within the struct's own methods, even if they're marked as mutating . Once a struct is constant, it is constant. It can't change. Structs aren't the only value types in Swift: Enums are value types, too.

Are structs copied by value?

We can now modify every property of those variables without affecting the other object, because the Dog struct contains basic types, which are copied by value.


2 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).

like image 146
BoltClock Avatar answered Sep 29 '22 12:09

BoltClock


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.

like image 40
Soner Gönül Avatar answered Sep 29 '22 11:09

Soner Gönül