C
C#2y ago
Hugh

❔ ✅ Generics 'where' : Limitations of what types are allows

When I'm specifying what types are allowed, is it possible to say anything about what types are not allowed. For example, I've got 2 use cases here:
class A {}
class B : A {}
class A2 : A {}
class B2 : B {}


// I want to say that T1 is *not* allowed to be a subclass of B
void DoSomething<T1, T2>(T1 val1, T2 val2)
where T1 : A
where T2 : B
{}

// I want to say that T1 and T2 are not allowed to be the same type
void DoSomethingElse<T1, T2>(T1 val1, T2 val2)
where T1 : A
where T2 : A
{}
class A {}
class B : A {}
class A2 : A {}
class B2 : B {}


// I want to say that T1 is *not* allowed to be a subclass of B
void DoSomething<T1, T2>(T1 val1, T2 val2)
where T1 : A
where T2 : B
{}

// I want to say that T1 and T2 are not allowed to be the same type
void DoSomethingElse<T1, T2>(T1 val1, T2 val2)
where T1 : A
where T2 : A
{}
Are either of this possible in C# at compile time?
6 Replies
Jayy
Jayy2y ago
no they are not at least not easily expressible, there might be a technically possible hacky way but im not sure
Anton
Anton2y ago
pretty sure there isn't
Hugh
Hugh2y ago
okay - thanks. I'll have to just be careful with how I use these functions then
Anton
Anton2y ago
do runtime checks on them
Hugh
Hugh2y ago
Yup - that's what I'm adding now Thanks
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts