Special/Short Hand Operators in C#

Special/Short Hand Operators in C#

Special/Short Hand Operators in C#

Since DOT NET moved from basic to higher side, Microsoft Introduced many short hand operators to help developers achieve quick programming skills. But people who are really not involved during updates are really not aware about these operators, what do they mean. Some developer just copy/paste the code and debug the final outcome, if it works they even don’t mind what exactly and how exactly these special operators work. Let’s see some operators which makes your programming shorten in nature:

?? (null-coalescing operator)

This is know as null-coalescing operator. The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

C# usage: a ?? b is roughly equivalent to this (except that the first argument is only evaluated once):

if (a == null)
     result = b;
     result = a;

or we can consider another usage like
(a == null) ? b : a

It is advisable for providing a default value, when a value can be null:

Color color = your.ChosenColor ?? defaultColor;

Linq example : When used in a LINQ to SQL query the ?? operator can be translated to a call to COALESCE. For example this LINQ query:

var query = objData.Select(x => x.Col1 ?? "default");

=> (Lambda operator)

This is know Lambda operator. It is used in lambda expressions to separate the input variables on the left side from the lambda body on the right side. Lambda expressions are inline expressions similar to anonymous methods but more flexible; they are used extensively in LINQ queries that are expressed in method syntax.

Code example:

string[] words = { "cherry", "apple", "blueberry" };  

// Use method syntax to apply a lambda expression to each element  
// of the words array.   
int shortestWordLength = words.Min(w => w.Length);  

// Output:   
// 5  

-> Operator: The -> operator combines pointer and member access.


Code Example: (where x is a pointer of type T* and y is a member of T) is equivalent to

// compile with: /unsafe

struct Point
    public int x, y;

class MainClass
    unsafe static void Main()
        Point pt = new Point();
        Point* pp = &pt;
        pp->x = 123;
        pp->y = 456;
        Console.WriteLine("{0} {1}", pt.x, pt.y);
123 456

For more details you can explore Microsoft portal to learn about operators here.

Next>>Encrypt/Decrypt string using C#

Leave a Reply

Your email address will not be published. Required fields are marked *