Dot Net For All

What is C# Expression

Many times while reading a C# book or reading any article you may encounter a word named expression. And you may start wondering what exactly is expression. In this article I will help you to understand what an expression is and different types of expressions.

C# expression

Lets see the official definition from the Microsoft website.

“An expression is a sequence of one or more operands and zero or more operators that can be evaluated to a single value, object, method, or namespace. “

Let simplify it and just say that a C# expression is a value. The simplest type of expression are constants and variables. Expressions can be combined using operators and transformed as well.

Below is an example of constant expression

12

We can use the * operator to combine two operands (the literal expressions 12 and 30), as follows:

12 * 30

Complex expressions can be built because an operand may itself be an expression, such as the operand (12 * 30) in the following example:

1 + (12 * 30)

Operators in C# can be classed as unarybinary, or ternary—depending on the number of operands they work on (one, two, or three). The binary operators always use infix notation, where the operator is placed between the two operands.

Primary Expression

There are the expression which are defined by the operators belonging to the language and framework. For example, have a look at the below code

Math.Pow(2, 2);

In the above code there are two operators. First one is the . (dot) operator which looks up for the Pow method defined in the Math class. This is expression performs a method look up. Other expression performs method call.

Void Expressions


A void expression is an expression that has no value. For example:

Console.WriteLine (1)


A void expression, since it has no value, cannot be used as an operand to build more complex expressions:

1 + Console.WriteLine (1)      // Compile-time error

Assignment Expressions


An assignment expression uses the = operator to assign the result of another expression to a variable. For example:

x = x * 5


An assignment expression is not a void expression—it has a value of whatever was assigned, and so can be incorporated into another expression. In the following example, the expression assigns 2 to x and 10 to y:

y = 5 * (x = 2)

This style of expression can be used to initialize multiple values:

a = b = c = d = 0


The compound assignment operators are syntactic shortcuts that combine assignment with another operator. For example:

x *= 2    // equivalent to x = x * 2
x <<= 1   // equivalent to x = x << 1

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview