The question mark syntax on a method call in C# is called the null-conditional operator, and it was introduced in C# 6.0.
It allows you to safely access properties and methods of an object that may be null, without causing a null reference exception. The syntax is ?.
, and you place it before the property or method you want to access.
Here's an example:
string name = person?.Name;
In this example, the ?.
operator is used to safely access the Name
property of the person
object. If person
is null, the expression will return null instead of throwing a null reference exception.
You can also use the null-conditional operator with method calls. Here's an example:
int? length = person?.GetName()?.Length;
In this example, the ?.
operator is used to safely call the GetName
method on the person
object. If person
is null, the entire expression will return null instead of throwing a null reference exception. If GetName
returns null, the Length
property will not be called, and the entire expression will return null.
The null-conditional operator is a useful feature in C# that helps you write more concise and robust code. However, it should be used with care, as it can make your code more difficult to read and understand if overused.
"C# code with question mark syntax on method call - What does it mean?"
?.
) to safely invoke a method on a potentially null object.string result = person?.GetName();
"C# code with question mark syntax and method with parameters - What does it mean?"
string result = person?.GetName("Mr.");
"C# code with question mark syntax and method chaining - What does it mean?"
int? length = person?.GetName()?.Length;
"C# code with question mark syntax on static method call - What does it mean?"
string result = Person?.GetDefaultName();
"C# code with question mark syntax on method call with return value - What does it mean?"
int? age = person?.GetAge() ?? 0;
"C# code with question mark syntax on method call and null coalescing - What does it mean?"
string name = person?.GetName() ?? "DefaultName";
"C# code with question mark syntax on method call and conditional logic - What does it mean?"
bool isValid = person?.IsDataValid() == true;
"C# code with question mark syntax on method call and event invocation - What does it mean?"
person?.OnDataUpdated?.Invoke(this, EventArgs.Empty);
"C# code with question mark syntax on method call and LINQ query - What does it mean?"
var validPersons = persons?.Where(p => p.IsValid()).ToList();
"C# code with question mark syntax on method call and custom extension method - What does it mean?"
var result = person?.CustomExtensionMethod()?.ProcessData();
assets browser-automation simple-oauth2 skew nexus standard-deviation chmod parse-platform keycloak c#-4.0