Follow us on X (Twitter)  Like us on Facebook  Connect with us on LinkedIn  Subscribe to our YouTube Channel  Subscribe to our WhatsApp Group

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

 

 

Have a question? Or, a comment? Let's Discuss it below...

dhgate

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.