Let's learn about default literal in C# 7.1

Visual Studio 2017 version 15.3 came with C# 7.1 support, which includes 'default' literal. In this post, we are going to learn about it. - Article authored by Kunal Chowdhury on , and was last updated on 2017-08-18T18:51:03Z.

Let's learn about default literal in C# 7.1
Follow us on:    Twitter  |  Mastodon  |  Facebook  |  WhatsApp  |  Telegram  |  Google News

If you are using Visual Studio 2017 version 15.3, it came with new improvements on top of C# 7.0, thus changing the version to 7.1. One of the new change in C# 7.1 is 'default' literal to avoid the redundant information while writing code.


In this post, we will learn about this improvement and will also cover how to use this. Continue reading to know about it.


Let's learn about default literal in C# 7.1


You may already know about the default(T) operator in C#. It's been used to get the default value of the specified type. The default literal in C# 7.1 is just a shorter form variation of the same, to reduce the redundant code.


The new expression, using the default literal, allows you to omit the the type and keep the code simple. But internally, it acts like default(T) only. An expression with this classification can be implicitly converted to any type, by a default-or-null literal conversion.


To know more about the C# 7.0 features, checkout my book 'Mastering Visual Studio 2017'.


Here's some examples to demonstrate how you used the default(T) operator earlier and how you can do the same using the default literal:


Old ways... using the 'default(T)' operator

Let's first see, how the old ways work, having the redundant declaration:

int count = default(int);
const string str = default(string);
ObservableCollection<Person> p = default(ObservableCollection<Person>);
List<Person> p = flag ? default(List<Person>) : GetPerson();
var person = flag ? default(List<Person>) : GetPerson();
public Person PersonDetails { get { return default(Person); } }
public void Process(List<Person> persons = default(List<Person>)) { }


New way... using the 'default' literal

Now, the same thing can be written using the new 'default' literal, which will not only reduce the redundant entries, but will also make the code clear:

int count = default;
const string str = default;
ObservableCollection<Person> p = default;
List<Person> p = flag ? default : GetPerson();
var person = flag ? default : GetPerson();
public Person PersonDetails { get { return default; } }
public void Process(List<Person> persons = default) { }


Was it clear? Do let me know, if you have any queries. To know more about the C# 7.0 features, checkout my book titled 'Mastering Visual Studio 2017'.