Click here to Skip to main content
15,882,055 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
It seems like this should be possible, but for the life of me I can't remember how.

Let's say I have a generic like:
C#
class jigger<T>
{
    public T DoSomething() {}
}

and I have classes, some of which inherit
C#
class blick : jigger<string>
{
}

C#
class flegh : jigger<bool>
{
}

C#
class klipsh : jigger<int>
{
}

C#
class smothy 
{
}

C#
class gribb 
{
}

and then I want to evaluate and cast:
C#
var mixedbag = new object[]
{
    blick, flegh, klipsh, smothy, gribb
};

foreach(var i in mixedbag)
{
    // This is what I can't figure out:
    if(i is jigger<>)
        (i as jigger<>).DoSomething();
}
Posted
Updated 22-Oct-12 14:03pm
v2

1 solution

What I do in this case is create an interface that is not generic. Seems to work well. Of course more stuff to deal with, but still means you can have generics of different types saved in a variable.

XML
Interface IJigger<T>
{
    T DoSomething();
}

class jigger<T> : IJigger
{
    public T DoSomething() {}
}


foreach(var i in mixedbag)
{
    // This is what I can't figure out:
    if(i is IJigger)
        ((IJigger)i).DoSomething();
}


Note: Using (i as jigger<>) really buys you nothing. Use cast instead. If (i as IJigger) is null you crash anyway.
 
Share this answer
 
v4
Comments
Sergey Alexandrovich Kryukov 22-Oct-12 21:04pm    
The last sentence is not accurate. OP did not suggest if (i as jigger), it was if (i is jigger); and first would not compile, and OP's would not crash. But you are right about redundant as operator; and your code is correct. The usage of as is different: it's a dynamic type check along with the cast:

SomeType someVariable = someObject as SomeType;
if (someVariable != null)
someVariable.YouCanBeSureThatYouCanDereferenceItAsItIsNotNull();


All of the above means violation of pure OOP, a sign of bad code design.

--SA
Clifford Nelson 23-Oct-12 12:13pm    
I did not have an issue with "if(i is jigger<>)" but with "(i as jigger<>).DoSomething();". Should have just done a cast instead of the "as"
Yvan Rodrigues 22-Oct-12 21:19pm    
Thanks. I would usually implement an interface too. I'll have to take a look at the actual code again to see why this wouldn't work.
Clifford Nelson 22-Oct-12 21:32pm    
I missed the return of T. The only thing you could do is use a return type of object. The only option would be is have T derive from something, and have an appropriate functionality. More than likely T would be derived from some type.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900