Home > OS >  C# - Is there a way to reference an enumeration declared in a generic class from another NON generic
C# - Is there a way to reference an enumeration declared in a generic class from another NON generic

Time:07-16

Lets say we have the following base class:

public abstract class Generic<T>() { }

then a child like:

public class GenericComparable<T> : Generic<T> where T : IComparable
{
    public enum Comparison
    {
        Equal,
        Greater,
        GreaterEqual,
        Less,
        LessEqual,
        NotEqual,
    }
}

and another child like:

public class GenericEquatable<T> : Generic<T> where T : IEquatable
{
    public enum Comparison
    {
        Equal,
        NotEqual,
    }
}

Let's imagine, now that I have a class NON generic that has to use one of the enumerations defined in one of the child classes. For example:

public class Example()
{
   public bool ExampleMethod(GenericComparable<>.Comparison comparison)
   {
      return true;
   }
}

How can I make this code to compile without the need of having the ExampleClass generic as well?

CodePudding user response:

You should reconsider your approach.

Note that for each type T, GenericComparable<T>.Comparison will be a different type, i.e. typeof(GenericComparable<int>.Comparison) != typeof(GenericComparable<long>.Comparison). So there is no single type like GenericComparable<>.Comparison.

Can you define the enum types outside of the classes?

CodePudding user response:

It is possible - the following is valid code:

class A<T>
{
    public enum B { C, D};
}

class E
{
    public bool Test<T>(A<T>.B b)
    {
        return (b == A<T>.B.D);
    }
}

Whether it is a good idea is another matter.

CodePudding user response:

Why not use a non-generic class as the base class of the generic one?
Why define Generic<T> in the first place?
Example code (in C#):

public abstract class Comparable
{
    public enum Comparison
    {
        Equal,
        Greater,
        GreaterEqual,
        Less,
        LessEqual,
        NotEqual,
    }
}
public class GenericComparable<T> : Comparable where T : IComparable
{}
public class Equatable
{
    public enum Comparison
    {
        Equal,
        NotEqual,
    }
}
public class GenericEquatable<T> : Equatable<T> where T : IEquatable
{}
public class Example
{
   public bool ExampleMethod(Comparable.Comparison comparison)
   {
      return true;
   }
}
  • Related