The difference between is and as operator is that:
An object can be cast to a certain type then is returns true otherwise false, but talking about as operator, it is used to cast an object to a specific type but if in any case it is unable to type cast that object, it returns Null.
Ex.
class Student
{
public int RollNumber { get; set; }
public string Name { get; set; }
}
class RegularStudent : Student
{
public int MonthlyAttendance { get; set; }
}
class CorrespondenceStudent : Student
{
public int AnualAttendance { get; set; }
}
protected void checkIs()
{
Student student = new Student
{
RollNumber = 123,
Name = "Gaurav"
};
// this will return true
if (student is Student)
{
Response.Write(student.Name + " is a student");
}
else
{
Response.Write(student.Name + " is not a student");
}
// this will return false
if (student is RegularStudent)
{
Response.Write(student.Name + " is a regular student");
}
else
{
Response.Write(student.Name + " is not a regular student");
}
}
protected void checkAs()
{
Student student = new Student
{
RollNumber = 123,
Name = "Gaurav"
};
RegularStudent regularStudent = student as RegularStudent;
// this will return true
if (regularStudent == null)
{
Response.Write("Student is not a RegularStudent");
}
else
{
Response.Write("Student is a RegularStudent");
}
}
Note : RegularStudent class is a derived type and the Base types to Derived type casting is not allowed but vise versa is possible.
0 Comment(s)