The is Operator
Some conversion attempts are not successful and raise an
The syntax of the is operator is the following:
The operator returns
For example:
The
InvalidCastException exception at run time. Instead of blindly attempting a conversion,
you can use the is operator to check whether a conversion would complete successfully.
The syntax of the is operator is the following:
[Class Object] is [Target Type]
The operator returns
true if class object can be successfully converted to the target type through any a reference, boxing, and unboxing conversion.
For example:
class Person
{
public string Name = "Anonymous";
public int Age = 25;
}
class Employee : Person { }
class Program
{
static void Main()
{
Employee bill = new Employee();
Person p;
// Check if variable bill can be converted to type Person
if( bill is Person )
{
p = bill;
Console.WriteLine("Person Info: " + p.Name + ", " + p.Age);
}
}
}
The
is operator can be used only for reference conversions and boxing and unboxing conversions. It cannot be used for user-defined conversions.
The as Operator
The
The syntax of the as operator is the following:
Since the as operator returns a reference expression, it can be used as the source for an assignment, for example:
Like the
as operator is like the cast operator, except that it does not raise an exception. If the conversion fails, rather than raising an exception,
it returns null.
The syntax of the as operator is the following:
[Class Object] as [Target Type]
Since the as operator returns a reference expression, it can be used as the source for an assignment, for example:
class Person
{
public string Name = "Anonymous";
public int Age = 25;
}
class Employee : Person { }
class Program
{
static void Main()
{
Employee bill = new Employee();
Person p;
p = bill as Person;
if( p != null )
{
Console.WriteLine("Person Info: " + p.Name + ", " + p.Age);
}
}
}
Like the
is operator, the as operator can be used only for reference conversions and boxing conversions. It cannot be used for
user-defined conversions or conversions to a value type.
0 comments:
Post a Comment