Questions tagged [null-propagation-operator]

The null-propagation operator, introduced in C# 6.0, eliminates the need for multiple null checks within a method call chain.

The null-propagation operator was introduced in C# 6.0.

It eliminates the need for multiple null checks within a method call chain, by returning null when the object it's being called on is null, instead of calling the target method (or accessing the target property) and throwing a NullReferenceException.

string name = null;

int? nameLength = name?.Length;  // stores null in nameLength

The benefit becomes more apparent when dealing with long call chains.

Imagine a series of simple classes defined as follows:

public class ClassRoom
{
    public List<Student> Students { get; set; }
}

public class Student
{
    public List<Subject> Subjects { get; set; }
}

public class Subject
{
    public string Name { get; set; }
}

Safely accessing the length of a subject name, when only provided with a ClassRoom, requires somewhat lengthy and repetitive code:

int? nameLength = null;

if (c != null
    && c.Students != null
    && c.Students.Count > 0
    && c.Students[0].Subjects != null
    && c.Students[0].Subjects.Count > 0
    && c.Students[0].Subjects[0].Name != null)
{
    nameLength = c.Students[0].Subjects[0].Name.Length;
}

The same code, rewritten using the null-propagation operator:

int? nameLength = c?.Students?[0].Subjects?[0].Name?.Length;
32 questions
110
votes
1 answer

Why can't I use the null propagation operator in lambda expressions?

I often use null propagating operator in my code because it gives me more readable code, specially in long queries I don't have to null-check every single class that is used. The following code throws a compile error that we can't use null…
Mohsen Sarkar
  • 5,562
  • 7
  • 41
  • 83
29
votes
3 answers

Operator '?' cannot be applied to operand of type 'T'

Trying to make Feature generic and then suddenly compiler said Operator '?' cannot be applied to operand of type 'T' Here is the code public abstract class Feature { public T Value { get { return GetValue?.Invoke(); } // here is…
Sinatr
  • 18,856
  • 9
  • 75
  • 248
28
votes
3 answers

C# 6.0 Null Propagation Operator & Property Assignment

This question has been completely overhauled in the interest of being thorough in explanation. I have noticed what appears to be quite a poor limitation of the null propagation operator in C# 6.0 in that you cannot call property setters against an…
Matthew Layton
  • 32,574
  • 37
  • 140
  • 255
25
votes
3 answers

Monadic null checking in C# 6.0

I stumbled across an interesting site, where some of the new (proposed) features of C# 6.0 are addressed. You may read it here: Probable C# 6.0 features. What I find particular interesting is the monadic null checking (also known as the…
RvdV79
  • 1,912
  • 15
  • 34
23
votes
4 answers

Null conditional operator to "nullify" array element existence

The new C# 6.0 null-conditional operator is a handy vehicle for writing more concise and less convoluted code. Assuming one has an array of customers, then you could get null instead of a length if customers is null using this (examples from…
Michael Sorens
  • 32,325
  • 20
  • 111
  • 165
18
votes
4 answers

Null propagation operator and foreach

Reading a lot about the Null propagation operator ?., I found no answer whether it is helpful in the following scenario. Code that throws: int[] values = null; foreach ( var i in values ) // Throws since values is null. { // ... } To make this…
Uwe Keim
  • 36,867
  • 50
  • 163
  • 268
11
votes
3 answers

Null propagation operator, out parameters and false compiler errors?

Let's assume I have a class that has a property of type Dictionary, that may be null. This compiles but the call to TryGetValue() could throw at a NullRef exception at runtime: MyClass c = ...; string…
Cristian Diaconescu
  • 31,686
  • 28
  • 127
  • 219
11
votes
2 answers

Conditional Access expression cannot be assigned - C# null-propagation += events

One of my favorite C# features added is the "null-propagation" in CS6. This has cleaned up so much code for many of us. I came across a situation where this doesn't appear to be possible. I am not sure why as I though the null-propagation was just…
TravisWhidden
  • 1,948
  • 1
  • 17
  • 37
9
votes
4 answers

How can I use the Nullable Operator with the Null Conditional operator?

Old Way int? myFavoriteNumber = 42; int total = 0; if (myfavoriteNumber.HasValue) total += myFavoriteNumber.Value *2; New way? int? myFavoriteNumber = 42; total += myFavoriteNumber?.Value *2; //fails
halfbit
  • 54,462
  • 46
  • 195
  • 426
6
votes
3 answers

await with null propagation System.NullReferenceException

I have the following code: await _user?.DisposeAsync(); Visual Studio highlights this code, saying 'Possible NullReferenceException' by the way, without await Visual Studio doesn't show this warning Why NullReferenceException is possible here?
6
votes
1 answer

.NET Native code crashes on constructor?.Invoke() (null-propagation)

After scratching my head for the better part of the day, I stumbled upon a very weird issue with .NET code that is compiled using .NET Native (used for Windows UWP apps). The following code works fine in any .NET runtime environment, including Mono,…
Philippe Leybaert
  • 155,903
  • 29
  • 200
  • 218
6
votes
2 answers

C# 6 null propagation what value is set when object is null

var result = myObject?.GetType(); In this scenario what would be the value of Result if myObject is null?
wishmaster
  • 1,223
  • 7
  • 15
5
votes
2 answers

Why is null propagation inconsistently propagating Nullable?

I'm specifically calling attention to null-propagation as it pertains to bool? and the use of a bool returning method. For example, consider the following: public static bool IsAttributedWith(this JsonProperty property) where…
David Pine
  • 21,735
  • 6
  • 69
  • 98
5
votes
1 answer

Why does null-propagation of Nullable return T and not Nullable?

Consider the following code: Nullable dt; dt. <-- Nullable dt?. <-- DateTime Null propagation returns T, rather than Nullable. How and why?
Matthew Layton
  • 32,574
  • 37
  • 140
  • 255
5
votes
1 answer

Error when using the null-propagating / null-conditional operator

I am running a .NET 4.5 project in VS 2013. Why is the following code in error? var w = Request.Properties["MS_HttpContext"] as System.Web.HttpContextWrapper; string IP = w?.Request.UserHostAddress; //fail to compile I found this code on this MSDN…
Old Geezer
  • 10,411
  • 21
  • 87
  • 156
1
2 3