tags:

views:

181

answers:

6

If I have a method with a parameter that's an interface, whats the fasts way to see if the interface's reference is of a specific generic type?

More specifically, if I have:

interface IVehicle{}

class Car<T> : IVehicle {}

CheckType(IVehicle param)
{
    // How do I check that param is Car<int>?
}

I'm also going to have to cast after the check. So if there is a way to kill 2 birds with one stone on this one let me know.

+10  A: 

To check if param is a Car<int> you can use "is" and "as" as normal:

CheckType(IVehicle param)
{
    Car<int> car = param as Car<int>;
    if (car != null)
    {
         ...
    }
}
Jon Skeet
Jon--Your C# book has been very helpful--thank you for it and the great interview on DNR. Given my history with your advice, I'm prone to just blindly believe you! Having said that, why isn't Nick's response (directly using is) the better way to do this?
rp
@rp: 'as' keyword attempts to cast, and if it can't give you a null value. The 'is' check will require you to do the work twice, as the cast after the is check is just as expensive as the 'is'. As does it all and only does it once.
Binary Worrier
@rp: Binary Worrier is exactly right. But don't take any advice blindly, whether from me or anyone else :) (Glad you liked the book though.)
Jon Skeet
Thank both very much.
rp
A: 

I often find that if my code requires me to write checks for specific types, I'm probably doing something wrong. You didn't give us enough context for us to give advice on this, though.

Does this meet your needs?

Car<int> carOfInt = param as Car<int>;
if (carOfInt != null)
{
    // .. yes, it's a Car<int>
}
Jay Bazuzi
A: 

Use the "as" operator to do it all in one shot. "as" will return either an object of the type you want, or null if what you're checking against doesn't match. This will only work for reference types, though.

interface IVehicle { }
class Car<T> : IVehicle 
{
    static Car<int> CheckType(IVehicle v)
    {
        return v as Car<int>;
    }
}

The "is" operator will let you test to see if v is an instance of Car<int>.

MrKurt
+3  A: 

Or, you can just do:

if(param is Car<int>)
{
    // Hey, I'm a Car<int>!
}
Nick
+1  A: 

Why not make this generic?

interface IVehicle{}

class Car<T> : IVehicle {

    public static bool CheckType(IVehicle param)
    {
        return param is Car<T>;
    }
}

...

Car<string> c1 = new Car<string>();
Car<int> c2 = new Car<int>();
Console.WriteLine(Car<int>.CheckType(c1));
Console.WriteLine(Car<int>.CheckType(c2));
bruno conde
Best solution IMHO.
Gary Willoughby
+1  A: 
Robert Giesecke