SledgeHammer
SledgeHammer

Reputation: 7736

Is it possible to have an optional type in Generics?

I've seen a few almost similiar questions, but not exactly what I'm going for here.

Assume:

class MyBaseClass
{
}

I also have:

class MyClass<T> : MyBaseClass
{
    void SomeFunc(T t1, T t2)
    {
    } 
}

Normally t1 and t2 should be the same type. However, I ran into an edge case where they are not, so I need a:

class MyClass<T1, T2> : MyBaseClass
{
}

Is it possible to just have the T1 / T2 version and somehow mark T2 as = to T1 by default unless its specified?

Right now I have 2 separate classes... just wondering if there is any syntatic sugar to combine them into one?

Upvotes: 1

Views: 88

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

You can derive one-argument MyClass<T> from two-argument class:

class MyBaseClass {
}

class MyClass<T1,T2> : MyBaseClass {
    void SomeFunc(T1 t1, T2 t2) {
    } 
}

class MyClass<T> : MyClass<T,T> {
}

Upvotes: 7

Related Questions