-1

I have an abstract class that takes a generic type parameter, so that the user can define correct functionality in child classes:

public abstract class Fruit<TFruit>{
    public abstract TFruit CutFruit();
    public abstract float TypeIndependentMethod();
}

An outside class wants to call a type-independent abstract method in the class, and it does not need to know the type parameter of the child class. It only wants to call that class's implementation of TypeIndependentMethod():

public class FruitLabeler
{
    public Fruit fruit = null;

    public void WriteLabel(){
        float f = fruit.TypeIndependentMethod();
    }
}

The issue is that I cannot declare public Fruit fruit without a type parameter, the compiler demands that I declare Fruit<Orange> fruit or Fruit<Apple> fruit, etc. But I don't want my FruitLabeler to only work for Oranges or Apples, I want it to work for any fruit.

How can I declare an instance of Fruit that is type-independent, or how can I call it's generic-type-independent methods?

user430481
  • 315
  • 1
  • 4
  • 14
  • 2
    it doesn't make sens, make non generic class for this ... also seems like [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Selvin Nov 11 '20 at 22:16
  • also `Fruit` is not natural ... as Apple is the Fruit not parameter of Fruit – Selvin Nov 11 '20 at 22:19
  • @Selvin Okay I over-abstracted the example, but the problem is still clear. There are methods that use the generic type, and other methods that do not. I need to call the methods that do not use the generic type from an outside class without knowing the generic type. – user430481 Nov 11 '20 at 22:22
  • 1
    _"How can I declare an instance of Fruit that is type-independent"_ -- the same way you do for any shared member in any OOP language: you create a base type (class or interface in C#) inherited or implemented by the type in question. See duplicate for one of many examples. – Peter Duniho Nov 11 '20 at 22:32

1 Answers1

1

If you introduce an IFruit interface for the type independent methods, you can then use IFruit fruit instead and call methods without knowing the type

 public abstract class Fruit<TFruit> : IFruit{
        public abstract TFruit CutFruit();
        public abstract float TypeIndependentMethod();
    }

    public interface IFruit
    {
        public float TypeIndependentMethod();
    }

    public class FruitLabeler
    {
        public IFruit fruit = null;

        public void WriteLabel(){
            float f = fruit.TypeIndependentMethod();
        }
    }
Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
  • Side note: base class would likely fit OP's requirement better - with the interface there is no guarantee that it is actually an instance of `Fruit`. – Alexei Levenkov Nov 11 '20 at 22:52