Kjara
Kjara

Reputation: 2902

how to use type (=static) members in a generic setting

I want to make a contract about static methods/properties in order to use them in a generic setting. Like this:

interface IAnimal {
    static string Sound;
}

class Dog : IAnimal {
    static string Sound => "woof";
}

class Cat : IAnimal {
    static string Sound => "meow";
}

class AnimalSoundExplainer<T> where T : IAnimal {

    // This does not work (but I would like it to):
    internal static void Explain() =>
        Console.WriteLine("Every " + typeof(T).Name + " makes " + T.Sound);
}

I would use it like this:

AnimalSoundExplainer<Dog>.Explain(); // should write "Every Dog makes woof"
AnimalSoundExplainer<Cat>.Explain(); // should write "Every Cat makes meow"
  1. How can I make that contract (so that I get compile errors if I do not fulfill the contract)? C#'s static interface members do not work that way; C# will always just use the (provided or not) implementation of IAnimal. It does allow implementing/overriding static members analog to non-static members.

  2. How can I make use of that contract inside a generic setting, i.e. how can I access theses members from a given generic type argument

Upvotes: 1

Views: 266

Answers (1)

canton7
canton7

Reputation: 42245

This functionality is called "static abstract members", and it is currently in preview in .NET 6.

If you're happy enabling preview functionality, the following works in .NET 6 preview:

interface IAnimal {
    static abstract string Sound { get; }
}

class Dog : IAnimal {
    public static string Sound => "woof";
}

class Cat : IAnimal {
    public static string Sound => "meow";
}

class AnimalSoundExplainer<T> where T : IAnimal {

    internal static void Explain() =>
        Console.WriteLine("Every " + typeof(T).Name + " makes " + T.Sound);
}

See it on SharpLab.

Upvotes: 2

Related Questions