Reputation: 6235
I have 3 classes that have almost same fields:
public DateTime Date { get; set; }
public long? Value { get; set; }
public (Enum1 or Enum2 or Enum3) Type { get; set; }
So for them I want to create some interface. But I don't know how to add Type
field to it.
Maybe it is impossible as Enums are value types and can be derived only from System.Enum, but maybe there are some solution.
Upvotes: 0
Views: 225
Reputation: 10695
You can use generics for that:
public enum TypeA { }
public enum TypeB { }
public enum TypeC { }
public interface I<T> where T : struct
{
DateTime Date { get; set; }
long? Value { get; set; }
T Type { get; set; }
}
public class A : I<TypeA>
{
DateTime Date { get; set; }
long? Value { get; set; }
public TypeA Type { get; set; }
}
public class B : I<TypeB>
{
DateTime Date { get; set; }
long? Value { get; set; }
public TypeB Type { get; set; }
}
public class C : I<TypeC>
{
DateTime Date { get; set; }
long? Value { get; set; }
public TypeC Type { get; set; }
}
Edit from the comments: If you are're already using C# 7.3, you can use
where T : struct, Enum
as constraint, where theEnum
constrains it to enums, but since it still allow theEnum
class (which is not an enum), you could keep thestruct
constraint as well.
Upvotes: 4