user3596113
user3596113

Reputation: 878

How to cast an object to color iff possible

I'm getting an object passed as a parameter and i want to cast it to Color if it is possible. Sometimes tho this object (value) cant be casted to Color... since i cannot just use:

Color color = value as Color;

and this line of code will throw an exception if the object cant be casted:

Color color = (Color)value;

and i dont want to use try..catch for this. I cannot think of a way to solve this problem.

Thanks for your help.

Upvotes: 3

Views: 100

Answers (2)

insilenzio
insilenzio

Reputation: 938

Use "is" keyword:

if(value is Color)
{
  //cast to Color
}

link to msdn

Upvotes: 0

Yurii
Yurii

Reputation: 4911

Use the is operator:

if (value is Color)
{
    Color color = (Color)value;
}

Upvotes: 8

Related Questions