How to set a default value for a variable in C #?

I want to set a variable to the default value if the assignment returns null or something else.

string a = GetValue();

if GetValue returns null, then I want to have a default value for the variable a, how to do it in C #. Do not try to use if.

Thanks for the time.

+3
source share
5 answers

Use a null coalescing operator.

string a = GetValue() ?? "Default";
+11
source
string a = GetValue() ?? "DefaultValue";
+1
source

This will

string a = GetValue() ?? "default value";
+1
source

How about this one?

string a = GetValue() != null ? GetValue() : "default";

0
source

string a = GetValue () == null? string.empty: GetValue ();

0
source

Source: https://habr.com/ru/post/1775832/


All Articles