28 February 2013 CI Team

 

At this place I want to give some additional information’s about the subject I’ve already written about in this article. It’s about how to show units in your code which are not given in the framework like file sizes (MB, GB), temperatures or unit of length. After I published the first article I received much feedback especially from Norbert and my coworker Erik Baum who got a little bit deeper into the subject. Erik improved the data type with some impressing features which I would like to present to you know:

Struct vs. class

image

The first question people are used to ask me was: Why didn’t you use a struct for the data type? I know Structs from C and for me they were like a forerunner of classes. I knew that there are also structs for C# but I didn’t know how and when I should use them.

Here the short answer:

You use structs to create types that act like integrated data types like for example DataTime. That’s exactly what we were looking for! The advantage is a lower Overhead and with that a reduced memory use. On the other hand structs are not able to do everything a class can. You can find a list in the MSDN.

Overloaded operators

image

If we are building a data type it would be nice if it is as easy to use as Datetime and so on. To use the operators +-/== they have to be overloaded. This is not too hard and it offers a lot of comfort for the user.

The implicit operator

image

The implicit operator offers the conversion of data types without the need to tell him to. With the help of this operator the following command is possible:

image

IComparable and IEquatable

image

We allow our structs to inherit from these two interfaces. If you implement them you will be able to use many cool framework features. For example the Sort function for Arrays and lists uses IComparable Interface and that’s why we are able to sort our lists like that:

image

The full code for the DataSize struct is available here.