Deep C# - Structs & Classes |
Written by Mike James | ||||
Monday, 08 November 2021 | ||||
Page 2 of 3
However, let’s look at this more closely because a
and this immediately creates a
The similar
creates only a reference variable. To make use of a
To make the difference even clearer, you can create other references to the same
Now
makes an independent copy of the struct If you think you follow, try predicting the values in each of the fields of this admittedly complicated set of assignments:
The answer is:
because The difference between the two types of behavior is usually expressed as value semantics versus reference semantics, i.e. is the variable the value or a reference to the value. The advice is that structs should be used for simple data types where value assignment seems natural and classes should be used for more advanced types where reference assignment is natural. If you want to use a class to store data then C# has a predefined record class that makes it particularly easy, but a ArraysValue semantics also has another spin-off when it comes to arrays and indeed other complex data types. When you create an array you always use something closer to reference-type semantics as in:
This creates 10 ints in a contiguous block of memory and this is very efficient. Now consider:
This creates a contiguous block of 10 reference variables of type To finish the array construction you have to use something like:
This, of course, is not as efficient because the 10 objects are created on the heap and have to be memory managed, but all object-oriented languages suffer from this type of problem. The good news is that C# treats arrays created using structs in the same way as simple types, i.e. using value semantics. For example:
immediately creates an array of 10 As long as you keep thinking of value types and reference types as being more or less the same, except that reference types don't automatically create the object they reference, you should follow and things should seem simple. Structs versus ClassesStructs are so important and versatile that, before moving on, it is worth saying a few words that compares and contrasts them to classes while we are on the topic. As you might expect of a value type, structs don’t support inheritance – they inherit from objects, but that’s the end of the inheritance hierarchy. They do support interfaces, however, more of which in Chapter 6. Also a struct can have methods, properties and constructors, but it can’t have a destructor. Its default, i.e. parameter-less, constructor can’t be changed and always initializes all its fields to the default value of
It is important to realize that this way of creating a There is a difference, however, and it is that the use of |
||||
Last Updated ( Monday, 08 November 2021 ) |