Search code examples
c#classtypesvirtualabstract

C# Override an abstract class' function with a different one with a "Class Type" return type


I am trying to create a class based on an abstract class and overwrite a function contained in the base class with another one that has a return type of "T" which is a type passed by the class.

e.g:

public abstract class DayInfo
{
    public virtual void GetInfo()
    {
        throw new NotImplementedException();
    }
}

public class DayInfo<T> : DayInfo
{
    private T info;
    public DayInfo(T data)
    {
        info = data;
    }

    public T GetInfo() // << This
    {
        return info;
    }
}

Examples:

1

DayInfo info = new DayInfo<String>("Blah");
String stuff = info.GetInfo();

2

DayInfo info = new DayInfo<int>(25);
int stuff = info.GetInfo();

Is there any way to achieve this?

Edit 1: I forgot to precise that I didn't used a class-passed type in the base class because I wanted to be able to use it as a generic type without having to define any type.

e.g:

public SortedDictionary<int, DayInfo> Data = new SortedDictionary<int, DayInfo>();

Edit 2:

Also, the point of the virtual function in the base class is that it will make the child classes throw an exception if the GetInfo() function is accessed but isn't overridden.


Solution

  • This can be produced with NVI pattern:

    public abstract class DayInfo
    {
      protected virtual void GetInfoCore() {
        throw new NotImplementedException();
      }
    
      // or
      // protected abstract void GetInfoCore();
    
      public void GetInfo() {
        GetInfoCore();
      }
    }
    
    public class DayInfo<T> : DayInfo
    {
      private T info;
    
      public DayInfo(T data) {
        info = data;
      }
    
      public new T GetInfo() { // << This
        return info;
      }
    
      protected override void GetInfoCore() {
        GetInfo();
      }
    }