Вопрос

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

Это было полезно?

Решение

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

Другие советы

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.

You can "new" an integer as well.
The difference is you CANT pass a reference class by value.

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top