var type, Expressions and Precedence in C#

Goud.Kv
Posted by in C# category on for Beginner level | Points: 250 | Views : 2112 red flag

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.
Recommendation
Read Parameters, ref and out modifiers in C# before this article.

Introduction

So far, we have seen parameters in C#. Let's see var, expressions and precedence in C# in this chapter.

Objective

The main objective of this article is to learn about var type, different types of expressions and precedence in C# programming.

var

var is an implicit type which is used instantly to declare and initialize a variable. It is a C# reference. var can be used instead of any keywords such as int, string, char etc.

                              

Example:
Below example explains the usage of var clearly,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Program
    {
        static void Main()
        {
            var a = "This is a string";  // string
            var b = new StringBuilder(); // string builder
            var c = (float)Math.PI;      // float
            var d = 'x';                 // char
            var i = 1;                   // int

            Console.WriteLine(a);  // This is a string
            Console.WriteLine(c);  // 3.14 as it is the value of PI 
            Console.WriteLine(d);  // x
            Console.WriteLine(i);  // 1
        }
    }
}
In the above code, we have used var to declare an integer, character, string, float etc. which performs all their actions.

Note: Please read the comments in the code,

Now, check the result in the console which looks like,


But this implicitly typed variables are statically typed variables. For example,
int i = 2;
i = 'a';    // gives compile time error because 'i' is declared as int.
Note: Please read the comments in the code,

Expressions

Expression is a value. There are two simple kinds of expressions, which are constants and variables. Operators are used to combine or to transform the expressions.

Constant expression: Constant expression is an expression which doesn't perform any operation and will be constant. Example,
5

Combining expressions with operators
,
Let's take an arithmetic operator and combine two operands like below,
5 * 12
In the above example, '*' is an operator used to combine two operands 5 and 12.

Complex expressions,
We can also create complex expressions like below,
100 - (5*12)
In the above example, we have '(5*12)' is an operand which itself behaves as an expression.

C# operators are derived as unary (one), binary (two) and ternary (three) depending on the no. of operands they work.
Binary operators always use infix notation in which the operator is placed between two operands.

Primary Expressions:
These are the simplest form of expressions. They include the expressions composed of operators.

Example:
Math.Equals(...)
In the above expression, we have two primary expressions. First one (with . operator) checks the member and second expressions calls the function with '()' operator.

Void Expressions:
These are the empty valued expressions which has no value. 

Example: 
Console.Write("Void");
In the above example, we are just printing something but there is no value declared.

Void Expressions cannot be used as operands for generating complex expressions. Such as,
Console.Write("Void") + 2; // Compile-time error
The above expression gives you the compile time error as the void expression we used has no value.

Assignment Expressions:
These type of expressions will perform the action and assigns the result of that expression to a variable by using '=' operator. 
Example:
a = a + 4
The above expression is a valid expression (not void) as it has an assigned value. It adds the numeric value '4' to a and stores the result in a.

Hence, it can be used in another expression such as,
b = 2 * (a = 3)
The above code assigns 3 to a and 6 to b.

Assignment expressions are used to initialize multiple values in the same expression. For example,
a = b = c = 5   // Which means a = 5, b = 5, c = 5

There are some compound assignment operators such as,
a += 4 // This means a = a + 4
These are known as the syntactic shortcuts.

Operator Precedence and Associativity

precedence and associativity determines the order of evaluation of an expression which has multiple operators. Priority of execution is given to the operators with higher precedence
If we have the same kind of operators in an expression, then associativity helps in determining the order of evaluation.

Precedence:
Let's take an example expression with multiple operators,
15 - 4 * 3
The above expression performs '*' first because of its higher precedence (BODMAS rule). So it becomes as,
15 - (4 * 3)
Associative:
All the binary operators are left associative except the assignment, lambda and null coalescing operators. 
Left-associative means they will execute from left to right.

Example:
4 * 2 * 2 // 16
This will be executed as,
(4 * 2) * 2  // 16
Now let's take another example like,
16 / 8 / 2
This should be evaluated as,
(16 / 8) / 2 // 1
If we change the order of evaluation,
16 / (8 / 4) // 8

Note: please see the difference in comments.

Right-associative operators are the assignment operators, null coalescing, lambda and conditional operators.

Example:
a = b = c = 5
The above expression assigns the value '5' to c (first) and then to b (right to left) and so on.

Conclusion

In this article, we have looked into 'var' and different types of expressions in C# programming. Hope you understand.

Thanks for reading.

Regards,
Krishna.

Recommendation
Read Statements and types of statements in C# after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Posted by: Vivek.Ramapuram on: 8/15/2014 | Points: 25
Happy Independence Day
Good posts .... Thank you vamsi Krishna ... it is very easy to understand to learn by your postings :)
have good day

Login to post response

Comment using Facebook(Author doesn't get notification)