Proposed New Features in C# 8: nullable reference types
C# 8’s new proposed enhancements
In C# 8 following language enhancements are proposed:
- Nullable Reference Types
- Async streams
- Default interface implementations
- Extension everything
In this article, we will look into one of the proposed enhancement: Nullable Reference Types
Nullable Reference Types
We already have syntax to specify nullable value-types that can be assigned the value of null.
T? where T is a value type.
In C# 8’s proposed language enhancements, it is planned to extend that to reference-types as well.
T? where T is a reference type.
So, now with C# 8’s proposed changes, we can specify whether the reference-types is intended to be null or not.
reference-types not intended to be null:
string address; // specifies that address is not intended to be null. address = null; // this will give warning.
reference-types intended to be null:
string? address; // specifies that address can be null. address = GetAddress();
Now, if we try to get length of “address”, without any check for null:
int length = address.Length;
compiler will give warning, if flow analysis cannot establish a non-null situation. To fix that we need to place a check for null before accessing the Length property.
int length = address?.Length ?? 0;
Places where developer is sure that the value can not be null but compiler (flow analysis) was not able to figure it out & still gives warning, he can use the “dammit” operator (x!).
int length = address!.Lenght;
for telling compiler that “address” will not be null.
Will share full working sample codes in my future posts on above enhancement once C# 8 enhancement are released. I am looking forward to see Nullable Reference Types in action.
Happy Coding !!!
.NET Professional | Microsoft Certified Professional | DZone’s Most Valuable Blogger | Web Developer | Author | Blogger
Doctorate in Computer Science and Engineering
Microsoft Certified Professional (MCP) with over 12+ years of software industry experience including development, implementation & deployment of applications in the .NET framework
Experienced and skilled Agile Developer with a strong record of excellent teamwork, successful coding & project management. Specialises in problem identification and proposal of alternative solutions. Provided knowledge and individual mentoring to team members as needed
Among top 3% overall in terms of contribution on Stack Overflow (~2.3 million people reached my posts). Part of the top 1% Stack Overflow answerers in ASP.NET technology.
DZone’s Most Valuable Blogger (MVB)
Created and actively maintain the TechCartNow.com tech blog while also editing, writing, and researching topics for publication.
Excellent skills in Application Development using C#/Vb.Net, .NET Framework, ASP.NET, MVC, ADO.NET, WCF, WPF, Web API, SQL Server, jQuery, Angular, React, BackboneJS