Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uniquess of methods and constraints

Tags:

c#

generics

I ran in to the following:

public void AddConfig<T>(Config c)  where T : BaseTypeA
{
// do stuff
}

public void AddConfig<T>(Config c)  where T : BaseTypeB
{
// do stuff
}

I would love to be able to do this. But i think it's impossible. The compiler ignores the constraints. Why? (I know it's by design).

I think my 2 options are:

  1. Make 2 distinct functions.
  2. Make 2 distinct Config classes.

Right?

like image 836
Jeroen Avatar asked Jul 08 '10 00:07

Jeroen


1 Answers

If you mean in the same class then you are correct (I don't think the compiler checks to make sure BaseTypeA and BaseTypeB can not be converted to each other which is what you would need to check to make sure they are unique methods, i.e. something like where T : BaseTypeA && T !: BaseTypeB if you get what I mean).

Having said that though, why aren't you doing something like this:

 interface IConfigurable
 {
      void AddConfig(Config c)
 }

 public class BaseTypeA : IConfigurable

 public class BaseTypeB : IConfigurable
like image 129
Matt Mitchell Avatar answered Oct 28 '22 21:10

Matt Mitchell