C# includes a decision-making operator ?: called the conditional operator or ternary operator. It is the short form of the if-else conditions. Syntax: condition ? statement 1 : statement 2 The ternary operator starts with a boolean condition. If this condition evaluates to true then it will execute the first statement after ?, otherwise the second statement after : will […]
Tag: Operator
The Null Conditional Operator in C# (?.)
The null conditional operator (?.) is colloquially referred to as the “Elvis operator” because of its resemblance to a pair of dark eyes under a large quiff of hair. The null conditional is a form of a member access operator (the .). Here’s a simplified explanation for the null conditional operator: The expression A?.B evaluates to B if the left operand (A) […]
The Null-Coalescing Operators in C# (?? and ??=)
The null-coalescing operator ?? returns the value of its left-hand operand if it isn’t null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn’t evaluate its right-hand operand if the left-hand operand evaluates to non-null. int? myValue = null; int result = myValue ?? -1; //result = -1; Syntax: p ?? q Here, p is […]
What does the word ‘new’ mean exactly in C#?
In C# (and many other languages) you will find that you use new often as it is fundamental to using types and classes. The new keyword does pretty much what it says: it will create a new instance of a class or type, assigning it a location in memory. Let me try and illustrate this. Company company; Here […]
Null-Conditional (?) and Null-Coalescing (??) Operators in C#
Null coalescing: The null coalescing operator “??” uses two question marks. With it you can use a custom value for a null reference variable. It simplifies null tests. C# program that uses null coalescing operator using System; class Program { static string _name; /// <summary> /// Property with custom value when null. /// </summary> static […]