tags:

views:

69

answers:

2

Hi,

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?

+4  A: 

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
Graphain
Nice angle. Haven't thought of that.
Jeroen
+4  A: 

Constraints are not a part of the signature. That's by design.

If you're interested in reading over a hundred comments from people who think that constraints should be part of the signature, check out the comments to my cleverly titled blog entry Constraints Are Not Part Of The Signature.

Eric Lippert
Good piece. I never ran in to that though.
Jeroen