C# Tips and Tricks (Part 3)

Qasim Asghar

In this final part of a 3 part series, Mohamad Lawand (https://www.mohamadlawand.com/) will be sharing C# tips and tricks you can use.

In this article we will be covering:

  • Async Main

  • Tuples

  • Value Equality for a class


You can watch the full video on YouTube here:



You can get the source code on GitHub:
https://github.com/mohamadlawand087/v35-ctte3


Async Main

This will allow us to add the async word into our main entry point, we can utilise it for

When we want to run async method from the main method, previously we could not await the main method. We need to do alot of wiring to make it work

So previously we need to something like this





New implementations




Tuples

A light wait syntex used to represent data. With tuples we remove the complexity of having classes and records. We can define simple data structure with multiple fields using tuples.

There is 2 types

  • Name tuple

  • Unnamed tuple

Although its a light weight syntax, it has really powerfull features that we can utilise

Named tuple where we specify the name of the field, so we declare a name variable. Now that i have specified the name of the field i can use it and refer to it when i utilise the tuple





Unnamed tuple, we are not giving a name for each feild and we utilise the generic way of calling the feilds inside the tuple by using item1 item 2





As well with tuple we can run equaliy operators





So basically it recognise what is this object and the data model of the object and all of the fields in it and still gives us the ability to compare.

How to define value equality for a class

When we define a class or struct, you decide whether it makes sense to create a custom definition of value equality (or equivalence) for the type.

Typically, we implement value equality when we expect to add objects of the type to a collection, or when their primary purpose is to store a set of fields or properties.


Our implementation should follow the five guarantees of equivalence (for the following rules, assume that xy and z are not null):

1. The reflexive property: x.Equals(x) returns true.

2. The symmetric property: x.Equals(y) returns the same value as y.Equals(x).

3. The transitive property: if (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true.

4. Successive invocations of x.Equals(y) return the same value as long as the objects referenced by x and y aren't modified.

5. Any non-null value isn't equal to null. However, x.Equals(y) throws an exception when x is null. That breaks rules 1 or 2, depending on the argument to Equals.