Constants are similar to read-only fields. You can’t change a constant value once it’s assigned. The const keyword precedes the field to define it as a constant. Assigning value to a constant would give a compilation error. For example:
const int num3 = 34;
num3 = 54;
// Compilation error: the left-hand side of an assignment must
// be a variable, property or indexer
Although constant are similar to read-only fields, some differences exist. You can also declare local variables to be constants. Constants are always static, even though you don’t use the static keyword explicitly, so they’re shared by all instances of the class.
Expressions and Operators
An 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 22 is a simple example of operators and operands.
Listing 22. The relationship between operators and operands
using System;
class Test
{
static void Main()
{
int num1 = 123;
int num2 = 34;
int res = num1 + num2;
Console.WriteLine(res.ToString());
res = -(res);
Console. WriteLine(res.ToString());
}
}
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 8 categorizes the operators. The table summarizes all operators in order of precedence from highest to lowest.
Table 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 & |
Logical | XOR ^ |
Logical | OR | |
Conditional | AND && |
Conditional | OR || |
Conditional | ?: |
Assignment | = *= /= %= += -= <<= >>= &= ^= |= |
| |
The checked and unchecked operators
The 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 operator
The 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 Operator
The 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.
Control Statements
Control flow and program logic are of the most important parts of a programming language’s dynamic behavior. In this section, I’ll cover control flow in C#. Most of the condition and looping statements in C# comes from c and C++. Those who are familiar with java will recognize most of them, as well.
The if . . .else Statement
The if . . .else statement is inherited from C and C++. The if . . .else statement is also known as a conditional statement. For example:
if (condition)
statement
else
statement
The if. . .section of the statement or statement block is executed when the condition is true; if it’s false, control goes to the else statement or statement block. You can have a nested if . . .else statement with one of more else blocks.
You can also apply conditional or ( || ) and conditional and (&&) operators to combine more then one condition. Listing 23 shows you how to use the if. . .else statement.
Listing 23. The if . . . else statement example
using System;
public class MyClass
{
public static void Main()
{
int num1 = 6;
int num2 = 23;
int res = num1 + num2;
if (res > 25)
{
res = res - 5;
Console.WriteLine("Result is more then 25");
}
else
{
res = 25;
Console.WriteLine("Result is less then 25");
}
bool b = true;
if (res > 25 || b)
Console.WriteLine("Res > 25 or b is true");
else if ( (res>25) && !b )
Console.WriteLine("Res > 25 and b is false");
else
Console.WriteLine("else condition");
}
}
The switch Statement
Like the if . . . statement, the switch statement is also a conditional statement. It executes the case part if it matches with the switch value. If the switch value doesn’t match the case value, the default option executes .The switch statement is similar to an if . . . statement with multiple. . .else conditions, but it tends to be more readable. Note that in C#, you can now switch on string, which is something C++ did not previously allow. See listing 24 for an example of a switch statement.
Listing 24. The switch statement example
int i = 3;
switch(i)
{
case1:
Console.WriteLine("one");
break;
case2:
Console.WriteLine("two");
break;
case3:
Console.WriteLine("three");
break;
case4:
Console.WriteLine("four");
break;
case5:
Console.WriteLine("five");
break;
default:
Console.WriteLine("None of the about");
break;
}
The for loop Statement
The for loop statement is probably one of the widely used control statements for performing iterations in a loop. It executes a statement in the loop until the given guard condition is true. The for loop statement is a pretest loop, which means it first tests if a condition is true and only executes if it is. You can use the ++ or – operators to provide forward or backward looping. The following is an example of a for loop statement:
// Loop will execute 10 times from 0 to 9
for (int i=0; i<10; i++)
{
Console.WriteLine(i.ToString( ) );
}
The while loop Statement
The while loop statement also falls in the conditional loop category. The while loop statement executes unit the while condition is true. It’s also a pretest loop, which means it first tests if a condition is true and only continues execution if it is in the example shown here, the while loop statement executes until the value of i is less then 10;
int i = 0;
while (i<10)
{
Console.WriteLine(i.ToString());
i++;
}
The do . . . while loop Statement
The do . . . while loop statement is a post- test loop, which means it executes a statement first and then checks if the condition is true. If the condition is true, the loop continues until the condition is false. As the name says, “do something while something is true.” This is an example of a do . . . while loop:
int i = 0;
do
{
Console.WriteLine(i.ToString());
i++;
} while (i<10);
The foreach loop statement
The foreach loop statement is new concept to C++ programmers but will be familiar to veteran visual basic programmers. The foreach loop enables you to iterate over each element of an array or each element of a collection. This is a simple example:
//foreach loop
string[] strArr = {"Mahesh", "Chand", "Test String"};
foreach (string str in strArr)
Console.WriteLine(str);
In this example, the loop will continue until the items in the array are finished. Many of the collection examples in this article will use this loop.
The go to statement
The goto statement is used when you need to jump to a particular code segment. It’s similar to the goto statement in visual basic or C++.
In the following code, if an item of array is found, the control goes to the level found and skips all code before that.
Most programmers avoid using the goto statement, but you may find a rare need for it. One such occasion is the use of fall-through on a switch statement. Fall- thought is the ability for the control flow to fall from one case statement directly into another by leaving out the break statement. In C#, fall-though in a switch statement is not allowed as it was in C++. However, if you explicitly tell the switch statement to go to the next label, it will perform a jump to the next case, essentially carrying out the same function as a fall-through. Note that when using a go to in a case statement, you don’t have to provide a break (in all other cases, a break statement is mandatory). in this is bill” and “sometimes I’m called William” are displayed on the screen:
Console.WriteLine("What is your name? ");
string name = Console.ReadLine();
switch(name)
{
case "Bill":
Console.WriteLine("My name is Bill.");
goto case "William";
case "William":
Console.WriteLine("Sometimes I’m called William.");
break;
case "Anne":
Console.WriteLine("My name is Anne. ");
break;
default:
break;
}
The break statement
The break statement exits from a loop or a switch immediately. The break statement is usually applicable when you need to release control of the loop after a certain condition is met, or if you want to exit from the loop without executing the rest of the loop structure. You use it in for, foreach, while, and do. . . while loop statements. The following code shows the break statement. If condition j == 0 is true control will exit from the loop:
for (int i=0; i<10; i++)
{
int j = i*i;
Console.WriteLine(i.ToString());
if (j == 9)
break;
Console.WriteLine(j.ToString());
}
The continue Statement
Similar to the break statement, the continue statement also works in for, foreach, while, and do . . . while statements. The continue statement causes the loop to exit from the current iteration and continue with the rest of the iterations in the loop. See the following code for an example:
for (int i=0; i<10; i++)
{
int j = i*i;
Console.WriteLine("i is "+ i.ToString());
if (j == 9)
Continue;
Console.WriteLine("j is "+ j.ToString());
}
In this code snippet, when the condition j == 9 is true, the control exits from the current iteration and moves to the next iteration.
Note: The break statement makes control exits the entire loop, but the continue statement only skips the current iteration.
The return Statement
The return statement returns from a method before the end of that method is reached. The return statement can either a value or not, depending on the method that calls it.
This is an example of a return statement that return nothing, and another where the return statement returns an integer value:
public static void Main()
{
int output = 9 + 6;
if ( output >= 12)
return;
Console.WriteLine ("Output less then 12");
}
public int Sum(int a, int b)
{
return a + b;
}
Previous           Next