Deep C# - Structs & Classes |
Written by Mike James | ||||
Monday, 08 November 2021 | ||||
Page 3 of 3
Simple TypesThe simple data types,
Each simple type also has methods of its own and even static methods. For example:
Of course, you can’t inherit from a simple type and they have other special features such there being literals of the same type, e.g. 10, 233.34 and so on. Simple types are structs in spirit only as the compiler takes care to make sure that they are implemented in an efficient manner. Notice that, as with a
results in a compiler error because
works perfectly because Value or Reference - Decide Early, Don't ChangeYou should by now understand the difference between a value and a reference type, but when do you use one in preference to another? In most cases this question is simply about using a
We might very well use a method to do some computation involving a private instance of this struct:
In this example no computation is performed - the struct is simply returned. Now if some other part of your program uses this method it might well go on and perform further manipulations on the returned value:
In this case everything works as you would expect. The struct is treated using value semantics and the Now consider the seemingly small change from a
The change to the
However, if the client program performs the same manipulation:
the result is very different. Now the object passed as the result is treated as a reference type and subject to reference semantics. This means that Clearly changing from a value type to a reference type and vice versa is a potentially deep structural change to a program because it changes value semantics into reference semantics. In Chapter But Not In This Extract
PostludeStructs are value types, but classes are reference types and never the twain shall meet. Well at least you should keep them well apart in your mind because they behave differently and they are for very different purposes. C#’s structs are more sophisticated than the same idea implemented in other languages and, partly to make up for this, we have two alternatives – the tuple and the record. Both are useful, but it is possible to become excessively addicted to the tuple as a way of temporarily packaging data into a single entity that can be passed around.
Deep C#Buy Now From Amazon Chapter List
Extra Material <ASIN:1871962714> <ASIN:B09FTLPTP9> To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info
|
||||
Last Updated ( Monday, 08 November 2021 ) |