(possibly) a simple question

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
 
J

Jon Skeet [C# MVP]

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.
 
S

Saurabh

Thanks Jon.

--Saurabh

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top