34

I am going brain dead on this; I have several List' defined, based on specific classes (c1, c2, c3...). I have a method that will process information on these lists. What I want to do is pass in the specific list, but have the method accept the generic list, and then via typeof determine what specific work to do. I know its possible, but I cant seem to get the syntax right on the method side. so, for example:

List<c1> c1var;
List<c2> c2var;
List<c3> c3var;

some_method(c1var);
some_method(c2var);
some_method(c3var);

class some_thing
some_method(List<> somevar)
if typeof(somevar).name = x then
esle if typeof(somevar).name = y then....

How do I set up the parameter list for the method?

thanks in advance R. Sanders

1
  • 2
    Quick question, why wouldn't you overload some_method to accept specific types of lists instead of doing typeof? Commented Jan 12, 2010 at 17:53

3 Answers 3

55

You need to declare some_method to be generic, as well.

void SomeMethod<T>(List<T> someList)
{
    if (typeof(T) == typeof(c1))
    {
         // etc
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Careful using typeof like that. That will check that the types are exactly the same without respecting the type hierarchy. As a result, something like MemoryStream and Stream will not evaluate to the same type (typeof(MemoryStream) == typeof(Stream) evaluates to false). This may be desired, but it's something to be aware of. Using the 'is' keyword is the typical way of evaluating types because "MemoryStream is Stream" will evaluate to true since they share the same object hierarchy.
11

Careful with the use of typeof(typ1) == typeof(typ2). That will test to see if the types are equivalent disregarding the type hierarchy.

For example:

typeof(MemoryStream) == typeof(Stream); // evaluates to false
new MemoryStream() is Stream; //evalutes to true

A better way to check to see if an object is of a type is to use the 'is' keyword. An example is below:

public static void RunSnippet()
{
    List<c1> m1 = new List<c1>();
    List<c2> m2 = new List<c2>();
    List<c3> m3 = new List<c3>();

    MyMeth(m1);
    MyMeth(m2);
    MyMeth(m3);
}

public static void MyMeth<T>(List<T> a)
{
    if (a is List<c1>)
    {
        WL("c1");
    }
    else if (a is List<c2>)
    {
        WL("c2");
    }
    else if (a is List<c3>)
    {
        WL("c3");
    }
}   

Comments

0

in the parameter section put List then try in the code switch(typeof(T){case typeof(int): break;})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.