1

This question has 2 parts, but first here is some example code:

public abstract class Animal
{
    public static string Sound_Made()
    {
        return "Unknown"
    }
}

public class Dog()
{
    public static string Sound_Made()
    {
        return "Woof"
    }
}

public class Cat()
{
    public static string Sound_Made()
    {
        return "Meow"
    }
}

Notice that the Sound_made is static, as it does not depend on the instance.

I tried to make a generic function of the following form:

public string Sound<T>()
{
    if (typeof(T).isSubclassOf(Animal))
    {
        return T.Sound_Made() // This doesn't work since T is generic 
    }
    else
    {
        return "This is not an animal."
    }
}

I also tried using: public string Sound<T>() where T : Animal but that doesn't allow me to add functionality for other classes, which I removed just to simplify my problem.

How would it be possible for me to call these functions in the generic function after verifying that they extend class Animal within said generic function?

Thank you!

KeistarP
  • 33
  • 4
  • You don't need generics, just basic polymorphism. But if you really want something that's independent of instances, consider using attributes. – madreflection Aug 26 '20 at 21:07
  • The Generics are used here mainly to allow the function to also handle things that aren't animals. So even with polymorphism, I would need to call the static function from a generic standpoint. – KeistarP Aug 26 '20 at 21:11
  • 6
    this sounds like an XY problem. I can almost guarantee there is a better way to achieve whatever it is that you are attempting to do, than this weird generic resolution of static methods. – Dave Aug 26 '20 at 21:14
  • 1
    Here is what you trying to do https://stackoverflow.com/questions/3384976/calling-a-static-method-using-a-type, but as everyone commented so far it does not sound like a reasonable design... – Alexei Levenkov Aug 26 '20 at 21:17
  • Thank you for all the support so far, sounds like I should redesign my program. – KeistarP Aug 26 '20 at 21:23

0 Answers0