In C# structs are value types, but I am able to new
them as if they are reference types. Why is this?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With