Tag Archives: C#

Global using in C# 10

In any C# application one common problem I noticed is, declare large number of using for namespaces in every .cs files. This has been taken care now by introducing global using in C# 10. Now you can declare common namespace using statements in single file and every file in that project can refer them. No need to declare large number of common using statements in every file.

Read more about global using here. Also there is a good YouTube tutorial on this.

I think this is a very nice feature.

The use of ‘var’ in C#

I don’t like to use var because it reduce the readability of code. Look at the below code.

var itemNumber = items.Count();

You can’t confirm the exact data type of itemNumber. It can be int or long or any other integer types. Many people says that IDE like Visual Studio shows you the data type when you hover mouse on it. Yes that is true. But what happen if you are not reading this code on Visual Studio? Many times we read code on GitHub or StackOverflow.

I think it always a good habit to use explicit data types.

int itemNumber = items.Count();

C# language specification says that, only use var when the data type is readable clearly from the right side of the assignment. In other cases use explicit data types.

Now there is a good alternative in C# 9.0 even when you are creating new object.

MyClass mc = new();

It is better than ‘var’.

var mc = new MyClass();

You need to use var in case you are creating an anonymous type.

var filteredPeople = from person in people
                     where person.IsAdult
                     select new 
                         Name = $"{person.FirstName} {person.LastName}",

foreach(var filteredPerson in filteredPeople)


Flattening object with AutoMapper

I blogged about basic concept of AutoMapper before. AutoMapper supports flattening complex object model into DTO or other simple object model. For example, domain model usually has complex object model with many associations between them, but view model has flat object model. We can map domain object model to view object model with AutoMapper’s flattening. If you follow the naming convention of your destination object model, then you don’t need to provide any configuration code to AutoMapper. AutoMapper work with convention based and map your object model from complex to flat/simple one.

Continue reading