c# interview questions and answers
Lección 11 de 15 · Part 11 What is the difference between is and as keyword in c# · Bases de datos
Part 11 What is the difference between is and as keyword in c#
Link for all dot net and sql server video tutorial playlists
http://www.youtube.com/user/kudvenkat/playlists
Link for slides, code samples and text version of the video
http://csharp-video-tutorials.blogspot.com/2014/05/part-11-what-is-difference-between-is_11.html
what is the difference between is and as keyword in C#
The is operator returns true if an object can be cast to a specific type, otherwise false.
The as operator attempts to cast an object to a specific type, and returns null if it fails.
Another way to cast an object is by using the cast operator. The cast operator throws an exception if the cast fails.
Example:
using System;
namespace Demo
{
class Program
{
static void Main()
{
Employee emp = new Employee
{
ID = 101,
Name = “Mark”
};
PermanentEmployee permanentEmployee = (PermanentEmployee)emp;
}
}
class Employee
{
public int ID { get; set; }
public string Name { get; set; }
}
class PermanentEmployee : Employee
{
public int AnnualSalary { get; set; }
}
}
The above program will throw the following exception
System.InvalidCastException: Unable to cast object of type’Demo.Employee’ to type ‘Demo.PermanentEmployee’
So, what is the difference between Cast operator and as operator?
as operator will not throw an exception if the cast fails, where as, cast operator will throw an exception.