![]() |
|
Operator is, as and readonly fields in C#, Free online C# Programming Tutorial... |
| Lessons | C# readonly, is, as |
|
The is operator The is operator supports run time type information. It is used to test if the expression is of certain type and evaluates to a Boolean result. It can be used as a conditional expression. It will return true if the expression is not NULL and the expression can be safely cast to type. The following example illustrates this concept: class horse {
}
class Cat {
}
if (o is horse)
Console.Writeline(“it’s a horse”);
else if (o is Cat)
Console.Writeline(“it’s a dog”);
else
Console.Writeline(“what is it?”);
The as operator The as operator attempts to cast a given operand to the requested type. The normal cast operation – (T) e – generates an InvalidCastException where there is no valid cast. The as operator does not throw an exception; instead the result returned is null as shown below: expression is type ? (type) expression : (type) null Readonly fields Readonly field are instance fields that cannot be assigned to. That is, their value is initialized only once and then cannot be modified. This is shown in the following example: class Pair
{
public Pair(int x, int y)
{
this.x = x;
this.y = y;
}
public void Reset()
{
x = 0; // compile time errors
y = 0;
}
private readonly int x, y; // this declares Pair as
// an immutable read only object
}
Next >>> Lesson No. 22: C# Delegates
|