www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons C# readonly, is, as Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Like the previous lesson, in this lesson too we will discuss some miscellaneous C# concepts. In this lesson we will introduce you to the is operator, as operator and the readonly fields.

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







Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.