C# Retrieving Classname in a static method - c#

Example:
namespace MyProgram.Testing
{
public class Test1
{
public void TestMethod()
{
String actualType = this.GetType().FullName.ToString();
return;
}
public static String GetInheritedClassName()
{
return System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName;
}
}
public class Test2 : Test1
{
}
public class Test3
{
String test2ClassName = Test2.GetInheritedClassName();
}
}
Anyway, I want it to return "MyProgram.Testing.Test2" but instead Test2.GetInheritedClassName() returns "MyProgram.Testing.Test1". What do I have to put into that static class to get it to return that (if possible)?

It's not possible. When you call Test2.GetInheritedClassName, it's actually Test1.GetInheritedClassName that is called, because Test2.GetInheritedClassName doesn't really exists (btw, some tools like Resharper would show a warning: Access to a static member of a type via a derived type)
Static members don't participate in inheritance, which is kind of logical since inheritance only makes sense when you're dealing with instances...

The code that's printing out the type is the base-class method. Except for rare Reflection scenarios such as you provide above, execution wouldn't be affected by whether the method is called using the derived type or the base type, so the system makes no distinction.
You could, however, get around this by defining a generic base type:
class ClassNameTesterBase<T>where T:ClassNameTester<T>
{
public static String getName() { return (typeof(T)).Name; }
}
and then defining the other types of interest:
class ClassNameTester1<T&gt : ClassNameTesterBase<T> ...
class ClassNameTester2<T&gt : ClassNameTester1<T> ...
One may then if desired define leaf classes:
class ClassNameTester1 : ClassNameTester1<ClassNameTester1> { }
class ClassNameTester2 : ClassNameTester2<ClassNameTester2> { }
One slight caveat here is that ClassNameTester2 derives its innards from from ClassNameTester1<T> but is not substitutable for anything having to do with the ClassNameTester1<ClassNameTester1>; if it's being used as a static class, though, that shouldn't be a problem.

Related

public static (const) in a generic .NET class

Is there a syntax trick to get to the constant in a generic class without specifying an (ad-hoc) type?
public class MyClass<T>{
public const string MyConstant = "fortytwo";
}
// I try to avoid this type specification.
var doeswork = MyClass<object>.MyConstant;
// Syntax similar to what I'd like to accomplish.
var doesnotwork = MyClass.MyConstant;
There is a caveat about the static variable (constant) not being shared between different types like MyClass<object> and MyClass<int> but my question is about possible available syntax trick.
Use a non-generic abstract parent class.
public abstract class MyClass
{
public const string MyConstant = "fortytwo";
}
public class MyClass<T> : MyClass
{
// stuff
}
var doeswork = MyClass.MyConstant;
That of course assumes that there's some reason the constant needs to be part of the generic class; if it has public accessibility, I'm not seeing a reason why you wouldn't just put it in a separate class.
Having a non-generic abstract parent class is a good idea for every generic class you make; the generic class is actually a template for the specific subtype classes, rather than a true parent, so having a true non-generic parent can make some techniques (such as, but certainly not limited to, this one) a lot easier.
Something like this works:
using System;
namespace Demo
{
public class MyClass // Use a non-generic base class for the non-generic bits.
{
public const string MyConstant = "fortytwo";
public static string MyString()
{
return MyConstant;
}
}
public class MyClass<T>: MyClass // Derive the generic class
{ // from the non-generic one.
public void Test(T item)
{
Console.WriteLine(MyConstant);
Console.WriteLine(item);
}
}
public static class Program
{
private static void Main()
{
Console.WriteLine(MyClass.MyConstant);
Console.WriteLine(MyClass.MyString());
}
}
}
This approach works for any static types or values that you want to provide which do not depend on the type parameter. It also works with static methods too.
(Note: If you don't want anybody to instantiate the base class, make it abstract.)

How to write a method that can be shared by two non-inherited class

I am having 2 classes, both having a same method(name + type +behavior) and a same property (name + type)
public class Country
{
public string Name { get; set; }
public void DisplayName()
{
Console.WriteLine(this.Name);
}
}
public class Person
{
public string Name { get; set; }
public void DisplayName()
{
Console.WriteLine(this.Name);
}
}
-- Person and Country classes are not allowed to inherit
In the above code you can see Person class has similar method(DisplayName) like Country class. I am looking for a way so that both classes can share the same method codes, i want to do this because in my real codes- Method which i want to share is very big and whenever i change code in one class i have to copy paste it in other class too. That i feel is not the correct way.
Please suggest how to resolve this problem.
You say they cannot inherit from a common base class, but you could add an interface, right? I suggest giving them each a common interface. Then define an extension method for that interface. The method will appear for each of them in VS.
(Assumption: this will work if the class members accessed by the extension methods are public or internal.)
interface IDisplayable
{
string Name {get; set;}
}
public class Country : IDisplayable
{
public string Name { get; set; }
}
public class Person : IDisplayable
{
public string Name { get; set; }
}
public static void DisplayName(this iDisplayable d)
{
return doSomeDisplayLogic(d.Name);
}
. . . And in the same class as your extension method, define (not as an extension method) a function doSomeDisplayLogic to do your common logic. (first-time gotcha: make sure the extension method is in the same Namespace or the its namespace is also included in the calling code.)
I don't know if you're new to extension methods or not. They are very powerful. (And like many powerful features, they can be abused). An extension method on an interface seems crazy at first, until you get straight in your head how extension methods really work. LINQ wouldn't work without this!
Update: I see your comment above that the classes can't inherit from a common class, because they are already inheriting from a common class (which I assume can't be messed with too much). I would like to point out an Option 2, based on this: Creating a new class that Country/Person/etc. will inherit from, that itself inherits from the existing common parent class. The existing base class would become a grandparent class, so to speak. This would become more the route to go if Country and Person have other common characteristics besides this DisplayName method. If DisplayName is all you're after, the Interface/Extension pattern might be better.
Define an interface
public interface INameable
{
string Name {get;}
}
then add an extension
public static class INameableExt
{
public static void DisplayName(this INameable n)
{
// do your thing
}
}
I would suggest to avoid Extension Methods in some cases, you can ran into a problem when you need slightly a different implementation for both classes and then you have to design a more generic solution, EM can cause the same issues like multiple inheritance does.
As more generic OOD solution I would suggest to extract this behaviour into a separate service class abstracted by an interface:
public interface IDisplayService()
{
void Display();
}
Then implement it and inject into both classes via constructor.
Also, instead of introducing the interfaces and new classes you can inject Action or Func<> via constructor or even property and then call this method by invoking an injected in delegate.
You could create either a static utility method DisplayName() that you pass the data needed for display, or use composition and move all properties and corresponding methods such as DisplayName() in a separate class - then use an instance of this class from both Country and Person.
You could implement a strategy pattern:
class DisplayNameStrategy<T> {
private readonly Func<T, string> nameSelector;
public void DisplayNameStrategy(Func<T, string> nameSelector) {
this.nameSelector = nameSelector;
}
public void abstract DisplayName(T t);
}
class WriteToConsoleDisplayNameStrategy<T> : DisplayNameStrategy<T> {
public void WriteToConsoleDisplayNameStrategy(Func<T, string> nameSelector)
: base(nameSelector) { }
public override void DisplayName(T t) {
Console.WriteLine(this.nameSelector(t));
}
public class Person {
private readonly DisplayNameStrategy<Person> displayNameStrategy =
new WriteToConsoleDisplayNameStrategy<Person>(x => x.Name);
public string Name { get; set; }
public void DisplayName() {
this.displayNameStrategy(this);
}
}
Note: it's probably better to inject the concrete strategy.
You could use composition: define an interface, a class that implements it, and then have Person and Country implement the interface by calling methods on the implementation class:
// the interface
public interface IName {
string Name { get; set; }
void DisplayName();
}
// a class that implements the interface with actual code
public class NameImpl : IName {
public string Name { get; set; }
public void DisplayName() {
Console.WriteLine(this.Name);
}
}
public class Country : IName {
// instance of the class that actually implements the interface
IName iname = new NameImpl();
// forward calls to implementation
public string Name {
get { return iname.Name; }
set { iname.Name = value; }
}
public void DisplayName() {
// forward calls to implementation
iname.DisplayName();
}
}
What I THINK you are asking for is multiple class inheritance which is not allowed in C#. (but can be with C++ which you are NOT doing).
All the others have identified doing an INTERFACE solution, and probably the best way to go. However, from your description, you have a SINGLE BLOCK of code that is identical regardless of the type of object being a person or a business. And your reference to a huge block of code, you don't want to copy/paste that same exact code among all the other classes that may be intended to use similar common "thing" to be done.
For simple example, you have a functionality that builds out a person's name and address (or business name and address). You have code that is expecting a name and up to 3 address lines, plus a city, state, zip code (or whatever else). So, the formatting of such name/address information is the same for a person vs a business. You don't want to copy this exact method over and over between the two. However, each individual class still has its own things that it is responsible for.
I know its a simple example for context, but I think gets the point across.
The problem with just defining an Interface is that it won't allow you to actually implement the CODE you are referring to.
From your sample, I would consider doing a combination of things.. Create a static class with methods on it that you might want as "globally" available. Allow a parameter to be passed into it of an instance of a class that has a type of interface all the others have expressed that will guarantee the incoming object has all the "pieces" of properties / methods you are expecting, and have IT operate on it as needed. Something like
public interface ITheyHaveInCommon
{
string Name;
string GetOtherValue();
int SomethingElse;
}
public class Person : ITheyHaveInCommon
{
// rest of your delcarations for the required contract elements
// of the ITheyHaveInCommon interface...
}
public class Country : ITheyHaveInCommon
{
// rest of your delcarations for the required contract elements
// of the ITheyHaveInCommon interface...
}
public static class MyGlobalFunctions
{
public static string CommonFunction1( ITheyHaveInCommon incomingParm )
{
// now, you can act on ANY type of control that uses the
// ITheyHaveInCommon interface...
string Test = incomingParm.Name
+ incomingParm.GetOtherValue()
+ incomingParm.SomethingElse.ToString();
// blah blah with whatever else is in your "huge" function
return Test;
}
}
warning: lots of untested code here, wild guessing mostly since i disagree with the base assumption "no inheritance".
something like this should help you. create a new static class and paste your code in here.
public static class Display
{
public static void DisplayName<T>(T obj)
{
if ((T is Person) || (T is Country) || (T is whateveryouwant))
{
//do stuff
}
}
}
in your classes, refactor ShowDisplayName() to call that with "this" as parameter.
...
public void DisplayName()
{
DisplayName(this);
}
...
I wonder why your classes are not allowed to inherit it from a base class, since that's imho the right-est way to solve this.
A couple of options:
Make both classes implement an interface for the common members (Name) and add an extension method for the behaviour (or just a normal static method)
Create methods which take an instance and a lambda exppession to access the comment members, e.g.
public static void Display<T>(T item, Func<T, string> nameGetter)
You'd then call it with (say)
DisplayHelper.Display(person, p => p.Name);
The interface solution is the cleaner one, but using a delegate is more flexible - you don't need to be able to change the classes involved, and you can cope with small variations (e.g. PersonName vs FooName vs Name)
You can define that big method in a separate class and then call the method in both the above classes. For a static method, you can call the method using classname.methodname() syntax.
For a non static method, you will have to do this:
classname obj=new classname();
obj.methodname();

How to store a reference to a static class?

So something like:
public static class StaticClass {}
public class InstanceClass
{
static StaticClass StaticProperty {get;set;}
public InstanceClass()
{
InstanceClass.StaticProperty = StaticClass;
}
}
I thought one could do this but the compiler returns these errors:
static types cannot be used as parameters
static types cannot be used as return types
EDIT: I know that this doesn't work, but why? I imagine StaticClass is stored somewhere in memory, so other variables could be allowed to refer to it at the same memory, right?
EDIT2: One of the use cases would be something like this:
Say you have 5 different static classes you have collected with no source code, and they do generic stuff, so you want to have convenient access to them through a single static class. You could do it like:
public static class GenericStuff
{
public LinearAlgebra LinearAlgebra {get;set;}
public StringUtilities String {get;set;}
public GeometryOps Geometry {get;set;}
}
And use it like:
GenericStuff.LinearAlgebra.GetAngleBetweenVectors(v0, v1);
Some other use cases you could think of.
Update: I am going to use my psychic powers to try and figure what I think you're trying to do.
I'm guessing you have a static class with some methods that you want to access from within another class. Is that right?
Something like this, in other words:
static class HelperMethods
{
public static void SomeHelperMethod();
}
...and what you want to do is something like this?
class SomeOtherClass
{
public void MethodThatUsesHelperMethod()
{
// You want to be able to have "Helper" mean "HelperMethods"?
Helper.SomeHelperMethod();
}
}
If I've interpreted you correctly, there's only one way (that I can think) to sort of accomplish what you're after. This would be to add a using declaration to effectively alias your static type:
// At top of file
using Helper = HelperMethods;
Note that if you do this, you're creating a file-wide alias. There's no way to alias classes at only the class level.
StaticClass is the name of the class. Your StaticProperty property expects an instance of the class, which will never exist because the class is static.
I'm actually surprised you can even have a property typed as a static class, since it represents a total impossibility. (Oh wait, you can't do that; that's what you were saying.)
You say you want to store a "reference to a static class"; I have to assume you mean that you want a reference to the Type object representing the class, in which case you should do this:
public Type StaticProperty { get; set; }
// ...
StaticProperty = typeof(StaticClass);
Static classes are both abstract and sealed (take a peek at the generated IL). So, you can't create an instance of it, and you can't subclass it to have instances of subclasses. That combination alone makes it impossible for you to ever have a reference to an instance of a static class.
Now, to have a reference to the static class work the way you want, you'd have to have metaclasses in C#, or some different kind of aliasing.
To achieve what you want today, you'd have to manually delegate all methods from a wrapper class to the desired static class, or abandon static typing and use dynamic:
public class StaticWrapper : DynamicObject {
Type _type;
public StaticWrapper(Type type) {
_type = type;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) {
var method = _type.GetMethod(binder.Name, BindingFlags.Static | BindingFlags.Public, null, args.Select(a => a.GetType()).ToArray(), null);
if (method == null) return base.TryInvokeMember(binder, args, out result);
result = method.Invoke(null, args);
return true;
}
// also do properties ...
}
Usage:
public static class GenericStuff {
public readonly dynamic LinearAlgebra = new StaticWrapper(typeof(LinearAlgebra));
public readonly dynamic String = new StaticWrapper(typeof(StringUtilities));
public readonly dynamic Geometry = new StaticWrapper(typeof(GeometryOps));
}
Section §8.7.12 of the C# specification reads:
Classes that are not intended to be
instantiated, and which contain only
static members should be declared as
static classes. Examples of such
classes are System.Console and
System.Environment. Static classes
are implicitly sealed and have no
instance constructors. Static classes
can be used only with the typeof
operator and to access elements of the
class. In particular, a static class
cannot be used as the type of a
variable or be used as a type argument
Because a static class has no constructors, you can't instantiate it. Because it is sealed you cannot subclass it and create an instance of a subclass. Even if you could subclass it you wouldn't be able to call the base constructor, and therefore you still couldn't instantiate it.
Since you cannot create an object of the type of a static class, it makes no sense to use it as a return type.
Since StaticClass is a type name, not an expression, you cannot pass it as a parameter (in your case, to the property setter). However, you can obtain an instance of the Type class that represents it with the expression typeof(StaticClass).
You cannot store a reference to a static class. You can only store references to instances, and there are no instances of static classes (although static classes may have instance members).
You should take another look at the MSDN page on static classes.
"A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself."
I think this is what you are trying to say:
Ok, if you don't want to instantiate it, then your C# needs a bit more tweaking. Assuming your static class implements a property and/or method
public static class StaticClass
{
public static string StaticProperty {get; private set; }
public static void StaticMethod() { //DoSomething }
}
You can forward the property and function definitions in the InstanceClass, notice that you must prefix the class name of the static to the methods/properties that you want to call.
public class InstanceClass
{
private string StaticProperty
{
get { return StaticClass.StaticProperty; }
}
private StaticMethod()
{
StaticClass.StaticMethod();
}
public InstanceClass()
{ }
}
I think that using InstanceClass as a wrapper like this is a bit complicated, and unecessary. I've found that its worth trying to minimize the need for static classes and methods in a codebase. They cause all sorts of headaches when trying to test and debug.
I believe using the namespace feature would be the best way to accomplish what you're trying to do.
LinearAlgebra.cs
namespace GenericStuff
{
public static class LinearAlgebra
{
public static TypeOfResult Function() { ... }
}
}
Strings.cs
namespace GenericStuff
{
public static class Strings
{
public static TypeOfResult Function() { ... }
}
}
Geometry.cs
namespace GenericStuff
{
public static class Geometry
{
public static TypeOfResult Function() { ... }
}
}
All of which can be invoked starting with GenericStuff
var s = GenericStuff.Strings.Random(7);
var identity = GenericStuff.LinearAlgebra.Identity(3);
var square = GenericStuff.Geometry.Square(5);
var area = square.Area();
You can't do this. A class is not an instance of itself. "Dog" is not a Dog. You could assign typeof(StaticClass) to a field of type Type:
static StaticClass StaticProperty {get; set}
InstanceClass.StaticProperty = typeof(StaticClass);
This lets you use reflection on the type.
What I believe the op wants is a way to access other classes easily via a "proxy" that you know of.
So, lets say you have a class called MapHelpers:
public class MapHelper
{
public static string CalculateNearLocation (Vector3 position){...}
}
And you have many other "Helpers" that you don't really remember and just want to have them easily accessible. And so, you want to "store" them inside your "Helpers" class, just so you can remember where you put them.
You can either do this :
public class Helpers
{
public class MapHelpers : MapHelper{}
}
And be able to access your MapHelper via :
Helpers.MapHelpers.CalculateNearLocation(pos)
Or do this :
public partial class Helpers
{
}
public partial class Helpers
{
public class MapHelper
{
public static string CalculateNearLocation (Vector3 position){...}
}
}
And be able to access it via :
Helpers.MapHelper.CalculateNearLocation(pos)
However, the first method, will give you a warning on your IDE (if you have that set) about accessing static methods via derived type.
Depends on what you want to achieve in the end.
If you want to just change one class but not on runtime but on compile time (i.e. the same version of static file is going to be used), then you can easily just configure your app or just make several versions of the same file with various implementations.
Such approach is useful for e.g. translations if you have them in a static files.

Getting the current type in a static, generic method?

I've got an abstract class like this;
public abstract PropertyBase
{
public static System.Type GetMyType()
{
return !!!SOME MAGIC HERE!!!
}
}
I'd like to subclass it, and when I call the static GetMyType(), I'd like to return the subclass's type. So if I declare a subtype;
public class ConcreteProperty: PropertyBase {}
then when I call
var typeName = ConcreteProperty.GetMyType().Name;
I expect 'typeName' to be set to "ConcreteProperty." I suspect there's no way to do it, but I'm interested if anyone out there knows a way to get this info.
(The particular problem I'm trying to solve is the verbosity of dependency properties in WPF; I'd love to be able to do something like this;
class NamedObject : DependencyObject
{
// declare a name property as a type, not an instance.
private class NameProperty : PropertyBase<string, NamedObject> { }
// call static methods on the class to read the property
public string Name
{
get { return NameProperty.Get(this); }
set { NameProperty.Set(this, value); }
}
}
And I almost have an implementation, but I can't quite get the info I need out of my NameProperty class.)
You can partially achieve (1-level of inheritance deep) using generics:
class PropertyBase<T>
{
public static Type GetMyType() { return typeof (T); }
}
// the base class is actually a generic specialized by the derived class type
class ConcreteProperty : PropertyBase<ConcreteProperty> { /* more code here */ }
// t == typeof(ConcreteProperty)
var t = ConcreteProperty.GetMyType();
The subclassing bit will not work, because a static method is tied to a type. It is a method of a type, not a method of an instance. The subtype does not contain the static methods of a base type, because they are different types and the static method is tied to the base type. Even though the compiler might allow you to call a static method of a base class as through a derived class, it will in reality call the method from the base class. It's just syntax sugar. For the same reason you cannot "override" static methods in subclasses because it would make little sense.
Just wondering why would need to do something like this?
var typeName = ConcreteProperty.GetMyType().Name;
Anyhow you know the type while calling the method, you can simply do this as well..
var typeName = typeof(ConcreteProperty).Name;
Just in case you need to do this, you can use "shadowing" to override the implementation of base class in child class.
public class ConcreteProperty : PropertyBase {
public new static Type GetMyType {
//provide a new implementation here
}
}

Why can't I have abstract static methods in C#?

I've been working with providers a fair bit lately, and I came across an interesting situation where I wanted to have an abstract class that had an abstract static method. I read a few posts on the topic, and it sort of made sense, but is there a nice clear explanation?
Static methods are not instantiated as such, they're just available without an object reference.
A call to a static method is done through the class name, not through an object reference, and the Intermediate Language (IL) code to call it will call the abstract method through the name of the class that defined it, not necessarily the name of the class you used.
Let me show an example.
With the following code:
public class A
{
public static void Test()
{
}
}
public class B : A
{
}
If you call B.Test, like this:
class Program
{
static void Main(string[] args)
{
B.Test();
}
}
Then the actual code inside the Main method is as follows:
.entrypoint
.maxstack 8
L0000: nop
L0001: call void ConsoleApplication1.A::Test()
L0006: nop
L0007: ret
As you can see, the call is made to A.Test, because it was the A class that defined it, and not to B.Test, even though you can write the code that way.
If you had class types, like in Delphi, where you can make a variable referring to a type and not an object, you would have more use for virtual and thus abstract static methods (and also constructors), but they aren't available and thus static calls are non-virtual in .NET.
I realize that the IL designers could allow the code to be compiled to call B.Test, and resolve the call at runtime, but it still wouldn't be virtual, as you would still have to write some kind of class name there.
Virtual methods, and thus abstract ones, are only useful when you're using a variable which, at runtime, can contain many different types of objects, and you thus want to call the right method for the current object you have in the variable. With static methods you need to go through a class name anyway, so the exact method to call is known at compile time because it can't and won't change.
Thus, virtual/abstract static methods are not available in .NET.
Static methods cannot be inherited or overridden, and that is why they can't be abstract. Since static methods are defined on the type, not the instance, of a class, they must be called explicitly on that type. So when you want to call a method on a child class, you need to use its name to call it. This makes inheritance irrelevant.
Assume you could, for a moment, inherit static methods. Imagine this scenario:
public static class Base
{
public static virtual int GetNumber() { return 5; }
}
public static class Child1 : Base
{
public static override int GetNumber() { return 1; }
}
public static class Child2 : Base
{
public static override int GetNumber() { return 2; }
}
If you call Base.GetNumber(), which method would be called? Which value returned? It's pretty easy to see that without creating instances of objects, inheritance is rather hard. Abstract methods without inheritance are just methods that don't have a body, so can't be called.
Another respondent (McDowell) said that polymorphism only works for object instances. That should be qualified; there are languages that do treat classes as instances of a "Class" or "Metaclass" type. These languages do support polymorphism for both instance and class (static) methods.
C#, like Java and C++ before it, is not such a language; the static keyword is used explicitly to denote that the method is statically-bound rather than dynamic/virtual.
With .NET 6 / C# 10/next/preview you are able to do exactly that with "Static abstract members in interfaces".
(At the time of writing the code compiles successfully but some IDEs have problems highlighting the code)
SharpLab Demo
using System;
namespace StaticAbstractTesting
{
public interface ISomeAbstractInterface
{
public abstract static string CallMe();
}
public class MyClassA : ISomeAbstractInterface
{
static string ISomeAbstractInterface.CallMe()
{
return "You called ClassA";
}
}
public class MyClassB : ISomeAbstractInterface
{
static string ISomeAbstractInterface.CallMe()
{
return "You called ClassB";
}
}
public class Program
{
public static void Main(string[] args)
{
UseStaticClassMethod<MyClassA>();
UseStaticClassMethod<MyClassB>();
}
public static void UseStaticClassMethod<T>() where T : ISomeAbstractInterface
{
Console.WriteLine($"{typeof(T).Name}.CallMe() result: {T.CallMe()}");
}
}
}
Since this is a major change in the runtime, the resulting IL code also looks really clean, which means that this is not just syntactic sugar.
public static void UseStaticClassMethodSimple<T>() where T : ISomeAbstractInterface {
IL_0000: constrained. !!T
IL_0006: call string StaticAbstractTesting.ISomeAbstractInterface::CallMe()
IL_000b: call void [System.Console]System.Console::WriteLine(string)
IL_0010: ret
}
Resources:
https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/static-abstract-interface-methods
https://github.com/dotnet/csharplang/issues/4436
Here is a situation where there is definitely a need for inheritance for static fields and methods:
abstract class Animal
{
protected static string[] legs;
static Animal() {
legs=new string[0];
}
public static void printLegs()
{
foreach (string leg in legs) {
print(leg);
}
}
}
class Human: Animal
{
static Human() {
legs=new string[] {"left leg", "right leg"};
}
}
class Dog: Animal
{
static Dog() {
legs=new string[] {"left foreleg", "right foreleg", "left hindleg", "right hindleg"};
}
}
public static void main() {
Dog.printLegs();
Human.printLegs();
}
//what is the output?
//does each subclass get its own copy of the array "legs"?
This question is 12 years old but it still needs to be given a better answer. As few noted in the comments and contrarily to what all answers pretend it would certainly make sense to have static abstract methods in C#. As philosopher Daniel Dennett put it, a failure of imagination is not an insight into necessity. There is a common mistake in not realizing that C# is not only an OOP language. A pure OOP perspective on a given concept leads to a restricted and in the current case misguided examination. Polymorphism is not only about subtying polymorphism: it also includes parametric polymorphism (aka generic programming) and C# has been supporting this for a long time now. Within this additional paradigm, abstract classes (and most types) are not only used to provide a type to instances. They can also be used as bounds for generic parameters; something that has been understood by users of certain languages (like for example Haskell, but also more recently Scala, Rust or Swift) for years.
In this context you may want to do something like this:
void Catch<TAnimal>() where TAnimal : Animal
{
string scientificName = TAnimal.ScientificName; // abstract static property
Console.WriteLine($"Let's catch some {scientificName}");
…
}
And here the capacity to express static members that can be specialized by subclasses totally makes sense!
Unfortunately C# does not allow abstract static members but I'd like to propose a pattern that can emulate them reasonably well. This pattern is not perfect (it imposes some restrictions on inheritance) but as far as I can tell it is typesafe.
The main idea is to associate an abstract companion class (here SpeciesFor<TAnimal>) to the one that should contain static abstract members (here Animal):
public abstract class SpeciesFor<TAnimal> where TAnimal : Animal
{
public static SpeciesFor<TAnimal> Instance { get { … } }
// abstract "static" members
public abstract string ScientificName { get; }
…
}
public abstract class Animal { … }
Now we would like to make this work:
void Catch<TAnimal>() where TAnimal : Animal
{
string scientificName = SpeciesFor<TAnimal>.Instance.ScientificName;
Console.WriteLine($"Let's catch some {scientificName}");
…
}
Of course we have two problems to solve:
How do we make sure an implementer of a subclass of Animal provides a specific instance of SpeciesFor<TAnimal> to this subclass?
How does the property SpeciesFor<TAnimal>.Instance retrieve this information?
Here is how we can solve 1:
public abstract class Animal<TSelf> where TSelf : Animal<TSelf>
{
private Animal(…) {}
public abstract class OfSpecies<TSpecies> : Animal<TSelf>
where TSpecies : SpeciesFor<TSelf>, new()
{
protected OfSpecies(…) : base(…) { }
}
…
}
By making the constructor of Animal<TSelf> private we make sure that all its subclasses are also subclasses of inner class Animal<TSelf>.OfSpecies<TSpecies>. So these subclasses must specify a TSpecies type that has a new() bound.
For 2 we can provide the following implementation:
public abstract class SpeciesFor<TAnimal> where TAnimal : Animal<TAnimal>
{
private static SpeciesFor<TAnimal> _instance;
public static SpeciesFor<TAnimal> Instance => _instance ??= MakeInstance();
private static SpeciesFor<TAnimal> MakeInstance()
{
Type t = typeof(TAnimal);
while (true)
{
if (t.IsConstructedGenericType
&& t.GetGenericTypeDefinition() == typeof(Animal<>.OfSpecies<>))
return (SpeciesFor<TAnimal>)Activator.CreateInstance(t.GenericTypeArguments[1]);
t = t.BaseType;
if (t == null)
throw new InvalidProgramException();
}
}
// abstract "static" members
public abstract string ScientificName { get; }
…
}
How do we know that the reflection code inside MakeInstance() never throws? As we've already said, almost all classes within the hierarchy of Animal<TSelf> are also subclasses of Animal<TSelf>.OfSpecies<TSpecies>. So we know that for these classes a specific TSpecies must be provided. This type is also necessarily constructible thanks to constraint : new(). But this still leaves out abstract types like Animal<Something> that have no associated species. Now we can convince ourself that the curiously recurring template pattern where TAnimal : Animal<TAnimal> makes it impossible to write SpeciesFor<Animal<Something>>.Instance as type Animal<Something> is never a subtype of Animal<Animal<Something>>.
Et voilà:
public class CatSpecies : SpeciesFor<Cat>
{
// overriden "static" members
public override string ScientificName => "Felis catus";
public override Cat CreateInVivoFromDnaTrappedInAmber() { … }
public override Cat Clone(Cat a) { … }
public override Cat Breed(Cat a1, Cat a2) { … }
}
public class Cat : Animal<Cat>.OfSpecies<CatSpecies>
{
// overriden members
public override string CuteName { get { … } }
}
public class DogSpecies : SpeciesFor<Dog>
{
// overriden "static" members
public override string ScientificName => "Canis lupus familiaris";
public override Dog CreateInVivoFromDnaTrappedInAmber() { … }
public override Dog Clone(Dog a) { … }
public override Dog Breed(Dog a1, Dog a2) { … }
}
public class Dog : Animal<Dog>.OfSpecies<DogSpecies>
{
// overriden members
public override string CuteName { get { … } }
}
public class Program
{
public static void Main()
{
ConductCrazyScientificExperimentsWith<Cat>();
ConductCrazyScientificExperimentsWith<Dog>();
ConductCrazyScientificExperimentsWith<Tyranosaurus>();
ConductCrazyScientificExperimentsWith<Wyvern>();
}
public static void ConductCrazyScientificExperimentsWith<TAnimal>()
where TAnimal : Animal<TAnimal>
{
// Look Ma! No animal instance polymorphism!
TAnimal a2039 = SpeciesFor<TAnimal>.Instance.CreateInVivoFromDnaTrappedInAmber();
TAnimal a2988 = SpeciesFor<TAnimal>.Instance.CreateInVivoFromDnaTrappedInAmber();
TAnimal a0400 = SpeciesFor<TAnimal>.Instance.Clone(a2988);
TAnimal a9477 = SpeciesFor<TAnimal>.Instance.Breed(a0400, a2039);
TAnimal a9404 = SpeciesFor<TAnimal>.Instance.Breed(a2988, a9477);
Console.WriteLine(
"The confederation of mad scientists is happy to announce the birth " +
$"of {a9404.CuteName}, our new {SpeciesFor<TAnimal>.Instance.ScientificName}.");
}
}
A limitation of this pattern is that it is not possible (as far as I can tell) to extend the class hierarchy in a satifying manner. For example we cannot introduce an intermediary Mammal class associated to a MammalClass companion. Another is that it does not work for static members in interfaces which would be more flexible than abstract classes.
To add to the previous explanations, static method calls are bound to a specific method at compile-time, which rather rules out polymorphic behavior.
We actually override static methods (in delphi), it's a bit ugly, but it works just fine for our needs.
We use it so the classes can have a list of their available objects without the class instance, for example, we have a method that looks like this:
class function AvailableObjects: string; override;
begin
Result := 'Object1, Object2';
end;
It's ugly but necessary, this way we can instantiate just what is needed, instead of having all the classes instantianted just to search for the available objects.
This was a simple example, but the application itself is a client-server application which has all the classes available in just one server, and multiple different clients which might not need everything the server has and will never need an object instance.
So this is much easier to maintain than having one different server application for each client.
Hope the example was clear.
The abstract methods are implicitly virtual. Abstract methods require an instance, but static methods do not have an instance. So, you can have a static method in an abstract class, it just cannot be static abstract (or abstract static).
It's available in C# 10 as a preview feature for now.

Categories