Constraint for classes defined inside a static class

Hello is there any way to constrain a generic method for classes which are defined inside a static class?

static class Container {
    class A {
    }
    class B {
    }
}

static class ContainerExtension
{
    //(where T  is a class defined in class Container)
    public int[] ToArray<T>(T array) {
    }
}
Jon Skeet
people
quotationmark

Is there any way to constrain a generic method for classes which are defined inside a static class?

No, there isn't.

The only type constraints are:

  • Requiring a public parameterless constructor (where T : new())
  • Requiring it to be a reference type (where T : class)
  • Requiring it to be a non-nullable value type (where T : struct)
  • Requiring an identity conversion to a particular type or type parameter (where T : Button or whatever)

There no constraint for "contained within a particular type" nor would I expect that to be a new feature on the way - it sounds like a very niche use case.

You could create an interface that only those types implement, but that's about as close as I can suggest. (If it's a private interface declared in the same containing class, only those classes could implement it - but then the generic method would need to be private too.)

people

See more on this question at Stackoverflow