Whether you’re still learning C# or you already have some experience, there will always be gaps in your knowledge, places where you are clueless as to your ignorance.
In the series of articles in C# Tips I will provide a whole host of useful information about the sometimes underused or unknown features of both C# and .NET.
In the previous article, we learned some tips for working with numbers and dates. In this article, we’re going to be learning about a whole host of different tips and tricks related to data types and objects in C# and .NET.
C# Data Types and Object Tips
- Using Tuples to Reduce the Amount of Code
- Creating and Using Combinable Enums
- Improving Struct Equality Performance
- Forcing Reference Equality Comparisons
Using Tuples to Reduce the Amount of Code
The Tuple class was introduced in .NET Framework 4.0. A tuple is a data structure that contains a sequence of elements of different data types. It can be used where you want to have a data structure to hold an object with properties, but you don’t want to create a separate type for it.
Let’s see some sample code
When you find yourself adding “out” parameters to your methods or creating a simple POCO or model to return multiple fields, you should consider using a Tuple.
However, traditional tuples have some limitations,
- A tuple is a reference type and not a value type. It allocates on the heap and could result in CPU intensive operations.
- The tuple is limited to include 8 elements. You need to use nested tuples if you need to store more elements. However, this may result in ambiguity.
- Tuple elements can be accessed using properties with a name pattern Item which does not make sense.
C# 7 includes ValueTuple to overcome the limitations of Tuple and also makes it even easier to work with Tuple. Let’s learn more about it,
C# 7.0 (.NET Framework 4.7) introduced ValueTuple, a structure which is a value type representation of the Tuple. Named parameters and better performance have made ValueTuple worth using.
The ValueTuple is only available in .NET Framework 4.7. If you don’t see ValueTuple in your project then you need to install the ValueTuple. (.NET Framework 4.7 or higher, or .NET Standard Library 2.0 or higher already includes ValueTuple.)
The following are examples of how to use ValueTuple.
We can now specify different member names for a ValueTuple returned from a method.
Also, ValueTuple now allows “discards” in deconstruction for the members you are not going to use.
In summary, if you have been holding out on using Tuples like me due to the lack of naming fields or performance issues before C# 7, it’s time to give them another chance.
Creating and Using Combinable Enums
Let’s take a look next to how we can create enums that we can combine to represent multiple options in a single enum value.
In the above program, we’re using a switch statement and depending on the enum value, we’re just adding the HTML tag element to the text.
Let’s take a look next to how we can create a version of this TextStyles that uses an enum that’s configured to allow the combination of its values.
In the above version, we added a class attribute Flags. Notice here, however, that I’m setting explicit values for each of these style options. We’re starting at 0 to represent normal, and then we’re defining the enum constants in powers of 2, So we start at 1, then we go to 2, if we added another option, that would be 4, and so on.
The reason we do this is so we can combine these enum constants to represent multiple options without the values overlapping. Like this,
Now, let’s update the switch program we had before and instead use if statements.
Let’s start by determining whether no processing is required. To do this, we can compare the options that were passed in,
Now, this Boolean will be set to true if the only style option is Normal.
But we don’t want to just say
style == TextStyles.Normal because the options that are going to be passed in may contain multiple enum values. Like this,
So, for example, the options passed in could represent both Bold and Underlined, so we can’t perform a straight equality comparison here. One way to check that the Bold option has been specified is to use a bitwise end and check the result is not equal to 0. Like this,
A more readable version, however, is to use the HasFlag method. Like this,
So our final program will now look like this,
Notice here to create a combination of enum values, we’re using the bitwise or operator. You can also do the same in Enums like this,
Note: Add the flags attribute if you’re creating an enum that represents a set of combinable flags as we’ve done here, you should add the flags attribute to indicate your intent as the developer and also provide better ToString functionality for enum values.
Improving Struct Equality Performance
The next tip we’re going to look at is the performance of structs, specifically their performance of equality comparisons.
In the above program, all we’re doing is calling the Equals method to compare two objects, and we’re performing this equality check inside a for loop just so we get more accurate numbers.
Now, these objects are of type structs. Here struct StructNoRef has only two property
Y, which are value types. And, StructWithRef is also a struct but it also has a additional property
Description which is a reference type. Like this,
Now if we run the program and test the time required to check the equality we will get result somewhat like this,
As you can see from the output struct with reference type members require 20 times more execution time than a struct with value type members
So why is this? Essentially, when checking for equality of two structs, if none of the fields in the struct are reference types, the Equals method performs a byte-by-byte comparison of the two objects in memory.
However, if there are reference types, reflection is used, and reflection is comparatively slow. So if you’ve got structs that contain reference types, you may want to look at the performance of equality checking.
But we can overcome this issue by overriding the Equals method. When we override the Equals method, we can provide our own code to determine whether two instances are equal. In this case, we’re comparing the X and Y values and also the string description. Like this,
Because we’ve overridden the Equals method, the default reflection‑based equality method won’t be used. So let’s come back to the test.
We can see when we override the Equals method, we reduce time to about 47 ms, which is a significant performance improvement if you’re doing a lot of equality checks.
So that’s how we can improve the performance of struct equality checks, by overriding the Equals method and preventing the default reflection-based approach from taking place.
Forcing Reference Equality Comparisons
For the final tip in this article, we’re going to see how we can check the two references point to the same object in memory.
In the above program, we’re creating two new instances of the Uri class. And if I just click on this and hit F12, we can see here that this Uri is a reference type, a class.
So even though a and b here are two separate instances and a and b point to two different places in memory, this areEqual Boolean is still being set to true. The reason for that is that the Uri class overrides the concept of equality.
Even though Uri is a reference type, a class, it overrides the reference equality semantics and instead provides value equality semantics. So as long as these two Uris point to the same website, for example, in this case, codewithshadman.com, they’re considered equal even though they point to different places in memory. So if a reference type is providing value equality semantics, such as the Uri class here, we’re still able to check if two references point to the same object.
So, We want to check whether or not a and b point to the same object, we’re going to call the ReferenceEquals method on the object class. To use this, we pass in the two references we want to check, in this case, a and b. And for good measure after this, let’s go and assign b to a and recheck if a and b point to the same reference.
Here, the object.ReferenceEquals method is telling us whether or not two references point to the same object in memory. And because a and b are different objects in memory, areEqual1 is returning false here.
And in the next step, we assigned b to a, both of these variables then point to the same object in memory, and so ReferenceEquals returns true.
So that’s how you can use object.ReferenceEquals to check that two reference types point to the same object in memory if the type is providing value equality semantics.
So that brings us to the end of this article. We started this article by looking at how tuples can help reduce the amount of code we need to write and maintain.
We then learned how to create combinable enums. To do this, we give the elements of the enum specific values, and once we’ve done this we can also create composites for commonly used combinations. In our code, we can use the HasFlag method to see if an enum contains a specific value, and when we’re creating combinable enums, we should apply the Flags attribute.
Next, we learned how to improve the performance of struct equality comparisons if those structs contain reference types. To do this, we override the Equals method. This prevents the reflection from being used and speeds up the equality check.
Finally, we learned how to use the object.ReferenceEquals method to determine whether two references point to the same item in memory. That’s it for now, join me in the next article by subscribing to my newsletter using the form below.
Type Comparison In C# - This post discusses different types of comparison methods, such as equality operators, object.equals method and IEquatable interface, used for comparing values in C#.
Subscribe to Code with Shadman
Get the latest posts delivered right to your inbox