check if value is null and set value if it is null in csharp

To check if a value is null and set a value if it is null in C#, you can use the null-coalescing operator (??).

Here's an example:

main.cs
string value = null;
string defaultValue = "Default Value";

string result = value ?? defaultValue;

Console.WriteLine(result);
128 chars
7 lines

In the above example, the value variable is assigned null. We then use the null-coalescing operator (??) to check if value is null. If it is null, defaultValue will be assigned to result. Since value is null, result will be assigned the value of defaultValue, which is "Default Value".

If value is not null, result will be assigned the value of value itself.

The output of the above code will be:

main.cs
Default Value
14 chars
2 lines

This way, you can easily check if a value is null and set a default value if it is null in C#.

related categories

gistlibby LogSnag