Search code examples
c#genericsstatic-methods

Can I call a static method that lives on a base class with a reference the the class implementing that base class (in C#)?


I'm having a hard time phrasing the question which is also making it hard for me to search for answers.

Here's a contrived scenario that mimics what I'd like to do:

void Main()
{
    Console.WriteLine(TestClassA.MyPropertyName());
    Console.WriteLine(TestClassB.MyPropertyName());
    
    var speaker = new TestSpeaker();
    speaker.Speak<TestClassA>();
    speaker.Speak<TestClassB>();
}

public class TestSpeaker {
    public void Speak<T>() where T : BaseClass<T> {
        Console.WriteLine(/* I want to call T.MyPropertyName() here */);
    }
}

public class TestClassA : BaseClass<TestClassA> {
    public string Name { get; set; }
}

public class TestClassB : BaseClass<TestClassB> {
    public string OtherPropertyName { get; set; }
    
}

public abstract class BaseClass<T> {

    public static string MyPropertyName(){
        return typeof(T).GetProperties().Single().Name;
    }
}

The Console right now would read:

Name
OtherPropertyName

I'd like to replace my commented out code so that it would read:

Name
OtherPropertyName
Name
OtherPropertyName

Solution

  • if you change your Writeline to

    Console.WriteLine(BaseClass<T>.MyPropertyName());

    you will get what you want