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

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

1 using System ; 2 using static System . Console ; 3 4 namespace csharp_data_types_and_object_tips 5 { 6 class Program1 7 { 8 public static void Run ( string [] args ) 9 { 10 Tuple < int , string , string > person1 = 11 new Tuple < int , string , string >( 1 , "Steve" , "Jobs" ); 12 WriteLine ( person1 . Item1 ); // returns 1 13 WriteLine ( person1 . Item2 ); // returns "Steve" 14 WriteLine ( person1 . Item3 ); // returns "Jobs" 15 16 var person2 = Tuple . Create ( 1 , "Steve" , "Jobs" ); 17 WriteLine ( person2 . Item1 ); // returns 1 18 WriteLine ( person2 . Item2 ); // returns "Steve" 19 WriteLine ( person2 . Item3 ); // returns "Jobs" 20 21 22 23 var numbers = Tuple . Create ( "One" , 2 , 3 , "Four" , 5 , "Six" , 7 , 8 ); 24 WriteLine ( numbers . Item1 ); // returns "One" 25 WriteLine ( numbers . Item2 ); // returns 2 26 WriteLine ( numbers . Item3 ); // returns 3 27 WriteLine ( numbers . Item4 ); // returns "Four" 28 WriteLine ( numbers . Item5 ); // returns 5 29 WriteLine ( numbers . Item6 ); // returns "Six" 30 WriteLine ( numbers . Item7 ); // returns 7 31 WriteLine ( numbers . Rest ); // returns (8) 32 WriteLine ( numbers . Rest . Item1 ); // returns 8 33 } 34 } 35 }

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,

Tuple 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.

But,

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.

1 using System ; 2 using static System . Console ; 3 4 namespace csharp_data_types_and_object_tips 5 { 6 class Program2 7 { 8 public static void Run ( string [] args ) 9 { 10 var person = ( 1 , "Bill" , "Gates" ); 11 WriteLine ( person . Item1 ); // returns 1 12 WriteLine ( person . Item2 ); // returns "Bill" 13 WriteLine ( person . Item3 ); // returns "Gates" 14 15 //equivalent Tuple 16 //var person = Tuple.Create(1, "Bill", "Gates"); 17 18 ValueTuple < int , string , string > person1 = ( 1 , "Bill" , "Gates" ); 19 WriteLine ( person1 . Item1 ); // returns 1 20 WriteLine ( person1 . Item2 ); // returns "Bill" 21 WriteLine ( person1 . Item3 ); // returns "Gates" 22 23 24 ( int , string , string ) person2 = ( 1 , "Bill" , "Gates" ); 25 WriteLine ( person2 . Item1 ); // returns 1 26 WriteLine ( person2 . Item2 ); // returns "Bill" 27 WriteLine ( person2 . Item3 ); // returns "Gates" 28 29 ( int Id , string FirstName , string LastName ) person3 = ( 1 , "Bill" , "Gates" ); 30 WriteLine ( person3 . Id ); // returns 1 31 WriteLine ( person3 . FirstName ); // returns "Bill" 32 WriteLine ( person3 . LastName ); // returns "Gates" 33 34 //We can also assign member names at the right side with values, as below. 35 var person4 = ( Id : 1 , FirstName : "Bill" , LastName : "Gates" ); 36 WriteLine ( person4 . Id ); // returns 1 37 WriteLine ( person4 . FirstName ); // returns "Bill" 38 WriteLine ( person4 . LastName ); // returns "Gates" 39 40 41 // PersonId, FName, LName will be ignored. 42 ( int Id , string FirstName , string LastName ) person5 = 43 ( PersonId : 1 , FName : "Bill" , LName : "Gates" ); 44 WriteLine ( person5 . Id ); // returns 1 45 WriteLine ( person5 . FirstName ); // returns "Bill" 46 WriteLine ( person5 . LastName ); // returns "Gates" 47 } 48 } 49 }

We can now specify different member names for a ValueTuple returned from a method.

1 using System ; 2 using static System . Console ; 3 4 namespace csharp_data_types_and_object_tips 5 { 6 class Program3 7 { 8 public static void Run ( string [] args ) 9 { 10 var person1 = GetPerson (); 11 WriteLine ( person1 . Id ); // returns 1 12 WriteLine ( person1 . FirstName ); // returns "Bill" 13 WriteLine ( person1 . LastName ); // returns "Gates" 14 15 ( var id , var fname , var lname ) = GetPerson (); 16 WriteLine ( id ); // returns 1 17 WriteLine ( fname ); // returns "Bill" 18 WriteLine ( lname ); // returns "Gates" 19 } 20 21 static ( int Id , string FirstName , string LastName ) GetPerson () 22 { 23 return ( 1 , "Bill" , "Gates" ); 24 } 25 } 26 }

Also, ValueTuple now allows “discards” in deconstruction for the members you are not going to use.

1 ( var id , var fname , _ ) = GetPerson (); // use discard _ for the unused member LastName

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.

1 using System ; 2 using static System . Console ; 3 4 namespace csharp_data_types_and_object_tips 5 { 6 public enum TextStyles 7 { 8 Normal , 9 Bold , 10 Italics , 11 Underlined , 12 } 13 14 class Program4 15 { 16 17 public static void Run ( string [] args ) 18 { 19 var style = TextStyles . Bold ; 20 var text = "Hello world!" ; 21 switch ( style ) 22 { 23 case TextStyles . Normal : 24 WriteLine ( $ "<span>{text}<span>" ); 25 break ; 26 27 case TextStyles . Bold : 28 WriteLine ( $ "<b>{text}<b>" ); 29 break ; 30 31 case TextStyles . Italics : 32 WriteLine ( $ "<i>{text}<i>" ); 33 break ; 34 case TextStyles . Underlined : 35 WriteLine ( $ "<strike>{text}<strike>" ); 36 break ; 37 } 38 } 39 } 40 } 41 42 //Output: 43 //<b>Hello world!<b>

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.

1 [Flags] 2 public enum TextStyles 3 { 4 Normal = 0 , 5 Bold = 1 , 6 Italics = 2 , 7 Underlined = 4 , 8 }

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,

1 var style = TextStyles . Bold | TextStyles . Underlined ;

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,

1 if ( style == TextStyles . Normal ) 2 { 3 text = $ "<span>{text}<span>" ; 4 }

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,

1 var style = TextStyles . Bold | TextStyles . Underlined ;

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,

1 if (( style & TextStyles . Bold ) != 0 ) 2 { 3 text = $ "<b>{text}<b>" ; 4 }

A more readable version, however, is to use the HasFlag method. Like this,

1 if ( style . HasFlag ( TextStyles . Bold )) 2 { 3 text = $ "<b>{text}<b>" ; 4 }

So our final program will now look like this,

1 using System ; 2 using static System . Console ; 3 4 namespace csharp_data_types_and_object_tips 5 { 6 class Program5 7 { 8 9 public static void Run ( string [] args ) 10 { 11 var style = TextStyles . Bold | TextStyles . Underlined ; 12 var text = "Hello world!" ; 13 if ( style . HasFlag ( TextStyles . Normal )) 14 { 15 text = $ "<span>{text}<span>" ; 16 } 17 18 if (( style & TextStyles . Bold ) != 0 ) 19 { 20 text = $ "<b>{text}<b>" ; 21 } 22 23 if ( style . HasFlag ( TextStyles . Italics )) 24 { 25 text = $ "<i>{text}<i>" ; 26 } 27 28 if ( style . HasFlag ( TextStyles . Underlined )) 29 { 30 text = $ "<strike>{text}<strike>" ; 31 } 32 33 WriteLine ( text ); 34 } 35 } 36 }

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,

1 [Flags] 2 public enum TextStyles 3 { 4 Normal = 0 , 5 Bold = 1 , 6 Italics = 2 , 7 Underlined = 4 , 8 BoldItalics = Bold | Italics //Combine option 9 }

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.

1 public static void Run ( string [] args ) 2 { 3 var stopwatch = new Stopwatch (); 4 var data1 = new StructNoRef (); 5 var data2 = new StructNoRef (); 6 stopwatch . Start (); 7 for ( int i = 0 ; i < 1000000 ; i ++) 8 { 9 data1 . Equals ( data2 ); //compare two objects 10 } 11 stopwatch . Stop (); 12 WriteLine ( "StructNoRef Comparison: " + stopwatch . ElapsedMilliseconds + " Milliseconds" ); 13 14 stopwatch . Reset (); 15 var data3 = new StructWithRef (); 16 var data4 = new StructWithRef (); 17 stopwatch . Start (); 18 for ( int i = 0 ; i < 1000000 ; i ++) 19 { 20 data3 . Equals ( data4 ); //compare two objects 21 } 22 stopwatch . Stop (); 23 WriteLine ( "StructWithRef Comparison: " + stopwatch . ElapsedMilliseconds + " Milliseconds" ); 24 }

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 X and 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,

1 struct StructNoRef 2 { 3 public int X { get ; set ; } 4 public int Y { get ; set ; } 5 } 6 7 struct StructWithRef 8 { 9 public int X { get ; set ; } 10 public int Y { get ; set ; } 11 public string Description { get ; set ; } 12 }

Now if we run the program and test the time required to check the equality we will get result somewhat like this,

1 StructNoRef Comparison: 45 Milliseconds 2 StructWithRef Comparison: 818 Milliseconds

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,

1 struct StructWithRef 2 { 3 public int X { get ; set ; } 4 public int Y { get ; set ; } 5 public string Description { get ; set ; } 6 7 public override bool Equals ( object obj ) 8 { 9 if (!( obj is StructWithRef )) 10 return false ; 11 12 var other = ( StructWithRef ) obj ; 13 14 return X == other . X && 15 Y == other . Y && 16 Description == other . Description ; 17 } 18 }

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.

1 StructNoRef Comparison: 48 Milliseconds 2 StructWithRef Comparison: 47 Milliseconds

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.

1 Uri a = new Uri ( "https://codewithshadman.com" ); 2 Uri b = new Uri ( "https://codewithshadman.com" ); 3 4 var areEqual = a == b ; 5 WriteLine ( areEqual ); //True

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.

1 Uri a = new Uri ( "https://codewithshadman.com" ); 2 Uri b = new Uri ( "https://codewithshadman.com" ); 3 4 var areEqual1 = Object . ReferenceEquals ( a , b ); 5 WriteLine ( areEqual1 ); //False 6 7 a = b ; 8 var areEqual2 = Object . ReferenceEquals ( a , b ); 9 WriteLine ( areEqual2 ); //True

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.

Summary

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.

Further Reading