(possibly) a simple question

  • Thread starter Thread starter Saurabh
  • Start date Start date
S

Saurabh

Hi All,

I quite like the idea of using the 'as' operator in C# and test for nullness
for example,

void MyFunction(Object o)
{
MyDataType dt = o as MyDataType;
if (dt == null)
{
DoSomething();
}
}

but I cannot use it on the value types. There is a similar situation as
above and I am expecting a System.Drawing.Point datatype whats the best way
to carry out the cast? Is it just cast it and catch the exception if it
throws an invalid cast exception.

Any comments / recommendations ?

TIA,

--Saurabh
 
Saurabh said:
I quite like the idea of using the 'as' operator in C# and test for nullness
for example,

void MyFunction(Object o)
{
MyDataType dt = o as MyDataType;
if (dt == null)
{
DoSomething();
}
}

but I cannot use it on the value types. There is a similar situation as
above and I am expecting a System.Drawing.Point datatype whats the best way
to carry out the cast? Is it just cast it and catch the exception if it
throws an invalid cast exception.

Use "is" and then cast. It's slower, as it basically involves casting
twice, but it's nicer than using an exception.
 
Back
Top