Thursday 25 June 2015

Use of ? in C#

You might be using ? in your code many times but when it gets specifically asked what is the use of ?
in C# then sometimes you not able to recall which makes this as an interview question.
Coming to the answer. Below are soem usage of "?" in C#

Nullable type :
To declare a nullable type ? is gets used.
e.g.
    int? num = null;

Nullable types are instances of the System.Nullable<T> struct. A nullable type can represent the correct
range of values for its underlying value type, plus an additional null value.

?? Operator (null-coalescing operator) which returns the left-hand operand if the operand is not null;
otherwise it returns the right hand operand. It mostly gets used with nullable types.   
int? x = null;
int y = x ?? -1;

In above example if x is null then y will have -1 value else x's value.

Conditional operator (?:)
? gets used in conditional operator which returns one of two values depending on the value of a Boolean expression.
   
int i = 6;
string str = (i >3 ? "yes": "no");

In above example conditional operator is used. So if i > 3 condition is true str will have value "yes" else value "no"