Files
freeCodeCamp/guide/english/csharp/null-coalescing-operator/index.md
Randell Dawson 0a1eeea424 fix(guide) Replace invalid prism code block names (#35961)
* fix: replace sh with shell

fix replace terminal with shell

fix replace node with js

fix replace output with shell

fix replace cs with csharp

fix replace c++ with cpp

fix replace c# with csharp

fix replace javasctipt with js

fix replace syntax  with js

fix replace unix with shell

fix replace linux with shell

fix replace java 8 with java

fix replace swift4 with swift

fix replace react.js with jsx

fix replace javascriot with js

fix replace javacsript with js

fix replace c++ -  with cpp

fix: corrected various typos

fix: replace Algorithm with nothing

fix: replace xaml with xml

fix: replace solidity with nothing

fix: replace c++ with cpp

fix: replace txt with shell

fix: replace code with json and css

fix: replace console with shell
2019-05-15 19:08:19 +02:00

76 lines
1.6 KiB
Markdown

---
title: Null-coalescing Operator
---
# Null-coalescing Operator
The null-coalescing operator in C# is used to help assign one variable to another and specify an alternate value if the source value is `null`. The null-coalescing operator in C# is `??`.
## Example 1
Since `name` is `null`, `clientName` will be assigned the value "John Doe".
```csharp
string name = null;
string clientName = name ?? "John Doe";
Console.WriteLine(clientName);
```
```csharp
> John Doe
```
## Example 2
Since `name` is not `null`, `clientName` will be assigned the value of `name`, which is "Jane Smith".
```csharp
string name = "Jane Smith";
string clientName = name ?? "John Doe";
Console.WriteLine(clientName);
```
```csharp
> Jane Smith
```
## Alternative to if...else Statement
You could use an `if...else` statement to test for the presence of `null` and assign a different value.
```csharp
string clientName;
if (name != null)
clientName = name;
else
clientName = "John Doe";
```
However, this can be greatly simplified using the null-coalescing operator.
```csharp
string clientName = name ?? "John Doe";
```
## Alternative to Conditional (Ternary) Operator
It is also possible to use the conditional operator to test for the presence of `null` and assign a different value.
```csharp
string clientName = name != null ? name : "John Doe";
```
Again, this can be simplified using the null-coalescing operator.
```csharp
string clientName = name ?? "John Doe";
```
## References
* [?? Operator (C# Reference)](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operator)