Expressions and OperatorsAn expression is a sequence of operators and operands that specify some sort of computation. The operators indicate an operation to be applied to one or two operands. For example, the operators + and - indicate adding and subtracting operands. For example, the operator + and- indicate adding and subtracting one object from another, respectively. Listing 1-22 is a simple example of operators and operands.
This example applies an operator on two objects, num1 and num2:int res = num1 + num2;There are three types of operators:
The unary operators take one operand and use either a prefix notation (Such as -x) or postfix notation (such as x++ ).
The binary operators take two operands and all use what is called infix notation, where the operator appears between two objects (such as x + y).
The ternary operator takes three operands and uses infix notation (such as c? x: y). Only one ternary operator, ?:, exists.
Table 1-8 categorizes the operators. The table summarizes all operators in order of precedence from highest to lowest.Table 1-8. Operators in C#
OPERATOR CAREGORY
OPERATORS
Primary
x.y f(x) a[x] x++ x-- new typeof checked unchecked
Unary
+ - ! ~ ++x --x (T)x
Multiplicative
* / %
Additive
+ -
Shift
<< >>
Relational and type testing
< > <= >= is as
Equality
== !=
Logical
AND &
XOR ^
OR |
Conditional
AND &&
OR ||
?:
Assignment
= *= /= %= += -= <<= >>= &= ^= |=
The checked and unchecked operatorsThe checked and unchecked operators are two new features in C# for C++ developers. These two operators force the CLR to handle stack overflow situations. The checked operators enforces overflow through an exception if an overflow occurs. The unchecked operator doesn't throw an exception if an overflow occurs. Here the code throws an exception in the case of the checked operator, whereas the unchecked part of the same code won't throw an exception:checked{num1 += 5;}unchecked{num =+ 5; }The is operatorThe is operator is useful when you need to check whether an object is compatible with a type. For example:string str = "Mahesh";if (str is object){Console.WriteLine(str +" is an object compatible");}
The sizeof OperatorThe sizeof operator determines the size of a type. This operator can only be used in an unsafe context. By default, an unsafe context is false in VS.NET, so you'll need to follow the right- click on the project > properties > Build option and set allow unsafe code blocks to use the unsafe block in your code. Then you'll be able to compile the following code:unsafe{ Console.WriteLine(sizeof(int));}
The typeof Operator The typeof operator returns the type of a class or variable. It's an alternative to GetType, discussed earlier in the "Objects in C#" section of this article.For example:Type t = typeof(MyClass);The GetType operator returns a Type Object, which can access the type name and other type property information.