paractical applications of the C# 'is' operator...

  • Thread starter Thread starter Neil Zanella
  • Start date Start date
N

Neil Zanella

Hello,

I would like to see some practical uses of the C# is operator.
This operator is not present in C++ and I would like to know
what some good uses of it are... after all if I declare a
variable as int, I know that it is an int, so there is
no point to writing stuff like:

int x = 0;
if (x is int)
Console.WriteLine("x is an integer.");


Thank you for your feedback,

Neil
 
Neil Zanella said:
Hello,

I would like to see some practical uses of the C# is operator.
This operator is not present in C++ and I would like to know
what some good uses of it are... after all if I declare a
variable as int, I know that it is an int, so there is
no point to writing stuff like:

int x = 0;
if (x is int)
Console.WriteLine("x is an integer.");

consider...

public void PrintObject(object o)
{
if (o is FinanceReport)
{
PrintFinanceReport((FinanceReport)o);
}
else if (o is EmployeeRecord)
{
PrintEmployeeRecord((EmployeeRecord)o);
}
}

(although you would often use 'as' or a table look up here for performance
reasons)

Its value is when the expression in question may hold a derived value
instead of a sealed type(like int is)
 
It's very useful when you start using polymorphism and interfaces.

Think about drag and drop. When an object is dropped on your control, you
want to see what that object "is", so you could write some code like:

if (dragItem is ToolBoxItem)
{
.ToolBoxItem toolBoxItem = (ToolBoxItem)dragItem;
...
}

Or perhaps you were iterating over objects in your form looking for objects
that support serialization?

foreach (Control ctl in Controls)
if (ctl is ISerializable)
...

You may know which controls support serialization seeing as you developed
the form, but sometimes it's better not to make assumptions because you may
change the form content later on.

It's particularly useful when you're provided with objects of which you're
not sure of the type of the object. Drag and drop, plug ins, or generic
routines you write that let you pass in a variety of object types.
 
Back
Top