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;
34 questions
176
votes
4 answers

An expression tree lambda may not contain a null propagating operator

The line price = co?.price ?? 0, in the following code gives me the above error, but if I remove ? from co.? it works fine. I was trying to follow this MSDN example where they are using ? on line select new { person.FirstName, PetName = subpet?.Name…
nam
  • 21,967
  • 37
  • 158
  • 332
118
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,910
  • 7
  • 47
  • 86
31
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
  • 20,892
  • 15
  • 90
  • 319
28
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
  • 35,361
  • 26
  • 116
  • 172
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
  • 39,871
  • 52
  • 185
  • 313
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
  • 2,002
  • 16
  • 36
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
  • 39,551
  • 56
  • 175
  • 291
15
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?
12
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
  • 2,142
  • 1
  • 19
  • 43
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
  • 34,633
  • 32
  • 143
  • 233
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
7
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
  • 168,566
  • 31
  • 210
  • 223
7
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,303
  • 8
  • 15
6
votes
1 answer

Use of unassigned local variable error is incorrectly indicated by compiler

Given this code: private void TryIt(Dictionary myDict) { if (myDict?.TryGetValue(1, out int myValue) ?? false) { Console.Out.WriteLine(myValue); // <-- Error CS0165 } } The c# compiler emits: error CS0165: Use of…
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
  • 23,787
  • 10
  • 79
  • 107
1
2 3