when would you use a struct??

+3 tony Davies · March 7, 2016
When would you use a struct??

Post a Reply


Oldest  Newest  Rating
0 Perverse Programmer · March 7, 2016
This quote comes from the C# language specification, which is surprisingly easy to read considering what it is. You can find it by googling "ECMA-334". If you're going to read this, read from section 8 (Language overview) and on...

The list of similarities between classes and structs is long—structs can implement interfaces, and can have the same kinds of members as classes. Structs differ from classes in several important ways, however: structs are value types rather than reference types, and inheritance is not supported for structs.

Now I expect you might ask, what is a value type and what is a reference type? The spec explains this too, in section 11:

Value types differ from reference types in that variables of the value types directly contain their data, whereas variables of the reference types store references to their data, the latter being known as objects. With reference types, it is possible for two variables to reference the same object, and thus possible for operations on one variable to affect the object referenced by the other variable. With value types, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other.

I would use a value type in place of a reference type when I want assignments to other variables to produce copies of the object, rather than merely using a copy of the reference to the same object. For example, int x = 42; int y = x; Both of these variables have the same value, but y refers to a different object than x; x and y have value types. As a tangential example, string foo = "bar"; string bar = foo; Both foo and bar have reference type, and they both refer to the same object...
0 M Jayanam · October 4, 2016
The most important difference is that a class is a referecne type, the struct a value type. This means when a value is assigned for the struct, the struct is copied.
  • 1



C# is an object-oriented language designed for improving the development of web applications.