KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
This is best illustrated with an example: class Cat { } class Dog { public static implicit operator Cat(Dog d) { return new Cat(); } } I want to tell, for an arbitrary object, if I can cast it to Cat. Sadly I cannot seem to use the is/as operator. void Main() { var d = new Dog(); if (d is Cat) throw new Exception("d is Cat"); var c1 = (Cat)d; // yes //var c2 = d as Cat; // Won't compile: Cannot convert type 'Dog' to 'Cat' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion } I'm hoping to avoid a try/catch(InvalidCastException) as I may be doing this a lot and this would be quite expensive. Is there a way to do this cheaply and easily? edit: Thanks for the answers guys - votes for all, wish I could give you all the Tick, but it's going to Marc for the most general solution (bonus vote for punching it out on an ipod). However Jordao's solution managed to hone in on what I need and not what I asked for so it is probably what I'm going with.
Tags (comma-separated)
Save Edits
Cancel