Can I create extensions in Java like I do in C#? [duplicate] - c#

This question already has answers here:
Java equivalent to C# extension methods
(14 answers)
Closed 9 years ago.
I am posting a C# example of extension usage, to make my question more clear. I have a simple class called Parameter with two properties: a key and a value. And I am extending the List of Parameters to be able to check if a certain key is contained in the List:
Parameter Class:
public class Parameter
{
private String key { get; set; }
private String value { get; set; }
}
Parameter Extension Class:
public static class ParameterListExtension
{
public static bool contain(this List<Parameter> parameters, String key)
{
foreach (Parameter parameter in parameters) {
if (parameter.key.Equals(key)) { return true; } }
return false;
}
}
Usage of Extension:
List<Parameter> parameters = getParameters();
if (parameters.contain("myParameter")) { ... }
Can this be done in Java?

There is an extension to Java, called Xtend, that adds support for extension methods (among other features). Some of the features of Xtend are supposed to come with Java 8. In my experiance, Xtend is sometimes nice, especially when writing tests, but the tool support in Ecplise is far worse than for pure Java. As far as I know there are no other IDEs supporting Xtend.

In Java 7 and earlier, there is no way to do this as described. The solution is to use a "helper" class as described in the other answers.
In Java 8, you can "sort of" do this using default methods. Consider the following:
public interface Parameter {
// getters and setters
}
public class ParameterImpl implements Parameter {
// Implements the getters and setters and the state variables.
}
Now suppose that we modify the Parameter as follows:
public interface Parameter {
// getters and setters as before
public default boolean contain(this List<Parameter> parameters, String key) {
// (Do not copy this! There are better ways to code this in Java 8 ...
// ... but that is beside the point.)
for (Parameter parameter : parameters) {
if (parameter.getKey().equals(key)) {
return true;
}
}
return false;
}
}
We can make this change to the interface (in the forward direction) without modifying the classes that implement the interface, and without breaking binary compatibility.
Of course, this only works if we had the foresight to create a separate interface and class. (But if we didn't do that, I would have thought is was no a "big deal" to modify the Parameter class to add the extension method.)

There is no such mechanism in Java to extend the behavior of a defined class out of your control. Alternatively, helper class and interface can be defined and used, though they don't 100% serve the purpose especially when visibility is a concern.

public class ParameterListExtension
{
public static boolean contain(List<Parameter> parameters, String key)
{
for(Parameter parameter:parameters)
if(parameter.key.equals(key)) return true;
return false;
}
}
…
import static ParameterListExtension.contain;
…
List<Parameter> parameters = getParameters();
if(contain(parameters, "myParameter")) { ... }
I don’t see the advantage of obfuscating where the method came from and pretending it was an instance method of the list.

Related

Is it a bad idea to use Generic Types to 'switch on types'? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Related to C# - Is there a better alternative than this to 'switch on type'?
I need to 'switch on types': given a parameter of type T, find and execute a method of the form void Method (T param).
This could be solved with a switch statement or a Dictionary<Type, Action>, however I would like to avoid the casts necessary in such scenarios.
I couldn't find the following approach mentioned in the above (or similar) questions:
Create a static generic type that acts as collection:
public static class Commands<T> {
public static Action<T> Handler;
}
Create a repository which uses that type like a type-safe dictionary:
public class CommandRepository {
public void Register<T>(Action<T> handler) {
Commands<T>.Handler = handler;
}
public void Run<T>(T parameter) {
// null checks etc.
Commands<T>.Handler(parameter);
}
}
Example usage:
public void CreateUser(CreateUserParams p) {
Console.WriteLine("Creating " + p.Name);
}
// ...
var repo = new CommandRepository();
repo.Register<CreateUserParams>(CreateUser);
repo.Register<DeleteUserParams>(DeleteUser);
repo.Run(new CreateUserParams { Name = "test" });
repo.Run(new DeleteUserParams { Name = "test" });
As mentioned before, the same behavior could be achieved with a Dictionary<Type, Action> in the ComandRepository, but then I would have to cast either the method parameter or, if I use interfaces instead of Action, cast to an IFoo<T> after acquiring an dictionary item.
My question is: Is it OK to (ab-)use generic types like that (given a large number of possible values for T)?
(Bonus question) If it isn't OK, why exactly not? What are the costs / negative effects this would cause?
A final note: I realize this doesn't work for type hierarchies or interfaces. Type T must be matched exactly, which in my scenario is fine.
Edit: I found out that Jil, a JSON serializer, also relies on this pattern. See the TypeCache type, which stores a delegate to serialize an object of type T (as far as I've understood from skimming through code). Since this TypeCache will store a large amount of types I suppose the pattern is generally not problematic.
It would still be interesting to know whether types or their static members need to be garbage collected or if there are other performance implications that need to be considered.
The approach you suggest is workable but has the disadvantage that your repository is effectively a singleton. If you ever find yourself needing a repository which doesn't behave like a singleton, you may find the ConditionalWeakTable[1] type helpful. The trick with using one of those is that for each type of interest you would have a singleton ConditionalWeakTable which maps your objects to the thing (if any) associated with that type. That class is only available in .NET 4.0, but can do some wonderful things.
[1] http://msdn.microsoft.com/en-us/library/dd287757.aspx
As an example, suppose one wanted a type OutTypeKeyedDictionary which supports a SetValue<T>(T Value) and bool TryGetValue<T>(out T Value). One could use a static class family OutputMappers<T>, each class of which which held a singleton instance of ConditionalWeakTable<OutTypeKeyedDictionary, T>. The OutTypeKeyedDictionary wouldn't actually have any fields(!); rather, each instance would be used purely as an identity token which would be used as a ConditionalWeakTable key. Incidentally, the reason that class is in the CompilerServices namespace rather than Collections is that it is used heavily by things like ExpandoObject.
The usual way to implement double dispatch in language like C# that provide only single dispatch, is the Visitor pattern. Your example would look as follows:
Interfaces:
interface IVisitor
{
void VisitCreateUserParams(CreateUserParams p);
void VisitDeleteUserParams(DeleteUserParams p);
}
interface IParams
{
void Accept(IVisitor visitor);
}
Command parameters:
class CreateUserParams : IParams
{
public void Accept(IVisitor visitor) { visitor.VisitCreateUserParams(this); }
public string Name { get; set; }
}
class DeleteUserParams : IParams
{
public void Accept(IVisitor visitor) { visitor.VisitDeleteUserParams(this); }
public string Name { get; set; }
}
Commands:
class CommandHandler : IVisitor
{
public void VisitCreateUserParams(CreateUserParams p)
{
Console.WriteLine("Creating " + p.Name);
}
public void VisitDeleteUserParams(DeleteUserParams p)
{
Console.WriteLine("Deleting " + p.Name);
}
}
Example usage:
var handler = new CommandHandler();
new CreateUserParams { Name = "test" }.Accept(handler);
new DeleteUserParams { Name = "test" }.Accept(handler);

C# Method Overload and Extension Methods [duplicate]

There have been occasions where I would want to override a method in a class with an extension method. Is there any way to do that in C#?
For example:
public static class StringExtension
{
public static int GetHashCode(this string inStr)
{
return MyHash(inStr);
}
}
A case where I've wanted to do this is to be able to store a hash of a string into a database and have that same value be used by all the classes that use the string class's hash (i.e. Dictionary, etc.) Since the built-in .NET hashing algorithm is not guaranteed to be compatible from one version of the framework to the next, I want to replace it with my own.
There are other cases I've run into where I'd want to override a class method with an extension method as well so it's not just specific to the string class or the GetHashCode method.
I know I could do this with subclassing off an existing class but it would be handy to be able to do it with an extension in a lot of cases.
No; an extension method never takes priority over an instance method with a suitable signature, and never participates in polymorphism (GetHashCode is a virtual method).
If the method has a different signature, then it can be done -- so in your case: no.
But otherwise you need to use inheritance to do what you are looking for.
As far as I know the answer is no, because an extension method is not an instance.It's more like an intellisense facility to me that let you call a static method using an instance of a class.
I think a solution to your problem can be an interceptor that intercepts the execution of a specific method (e.g. GetHashCode()) and do something else.To use such an interceptor (like the one Castle Project provides) all objects should be instansiated using an object factory (or an IoC container in Castle) so that thier interfaces can be intercepted through a dynamic proxy generated in runtime.(Caslte also lets you intercept virtual members of classes)
I have found a way to invoke an extension method with the same signature as a class method, however it does not seem very elegant. When playing around with extension methods I noticed some undocumented behavior. Sample code:
public static class TestableExtensions
{
public static string GetDesc(this ITestable ele)
{
return "Extension GetDesc";
}
public static void ValDesc(this ITestable ele, string choice)
{
if (choice == "ext def")
{
Console.WriteLine($"Base.Ext.Ext.GetDesc: {ele.GetDesc()}");
}
else if (choice == "ext base" && ele is BaseTest b)
{
Console.WriteLine($"Base.Ext.Base.GetDesc: {b.BaseFunc()}");
}
}
public static string ExtFunc(this ITestable ele)
{
return ele.GetDesc();
}
public static void ExtAction(this ITestable ele, string choice)
{
ele.ValDesc(choice);
}
}
public interface ITestable
{
}
public class BaseTest : ITestable
{
public string GetDesc()
{
return "Base GetDesc";
}
public void ValDesc(string choice)
{
if (choice == "")
{
Console.WriteLine($"Base.GetDesc: {GetDesc()}");
}
else if (choice == "ext")
{
Console.WriteLine($"Base.Ext.GetDesc: {this.ExtFunc()}");
}
else
{
this.ExtAction(choice);
}
}
public string BaseFunc()
{
return GetDesc();
}
}
What I noticed was that if I called a second method from inside an extension method, it would call the extension method that matched the signature even if there was a class method that also matched the signature. For example in the code above, when I call ExtFunc(), which in turn calls ele.GetDesc(), I get the return string "Extension GetDesc" instead of the string "Base GetDesc" that we would expect.
Testing the code:
var bt = new BaseTest();
bt.ValDesc("");
//Output is Base.GetDesc: Base GetDesc
bt.ValDesc("ext");
//Output is Base.Ext.GetDesc: Extension GetDesc
bt.ValDesc("ext def");
//Output is Base.Ext.Ext.GetDesc: Extension GetDesc
bt.ValDesc("ext base");
//Output is Base.Ext.Base.GetDesc: Base GetDesc
This allows you to bounce back and forth between class methods and extension methods at will, but requires the addition of duplicate "pass-through" methods to get you into the "scope" you desire. I am calling it scope here for lack of a better word. Hopefully someone can let me know what it is actually called.
You might have guessed by my "pass-through" method names that I also toyed with the idea of passing delegates to them in the hopes that a single method or two could act as a pass-through for multiple methods with the same signature. Unfortunately it was not to be as once the delegate was unpacked it always chose the class method over the extension method even from inside another extension method. "Scope" no longer mattered. I have not used Action and Func delegates very much though so maybe someone more experienced could figure that part out.

Can I use more generic interfaces to simplify my classes to use a command pattern?

I'm trying to make an app I'm designing more generic and implement the command pattern into it to use manager classes to invoke methods exposed by interfaces.
I have several classes with the GetItem() and GetList() methods in them, some are overloaded. They accept different parameters as I was trying to use dependency injection, and they return different types. Here are a couple of examples:
class DatastoreHelper
{
public Datastore GetItem(string DatastoreName)
{
// return new Datastore(); from somewhere
}
public Datastore GetItem(int DatastoreID)
{
// return new Datastore(); from somewhere
}
public List<Datastore> GetList()
{
// return List<Datastore>(); from somewhere
}
public List<Datastore> GetList(HostSystem myHostSystem)
{
// return List<Datastore>(); from somewhere
}
}
class HostSystemHelper
{
public HostSystem GetItem(int HostSystemID)
{
// return new HostSystem(); from somewhere
}
public List<HostSystem> GetList(string ClusterName)
{
//return new List<HostSystem>(); from somewhere
}
}
I'm trying to figure out if I could use a generic interface for these two methods, and a manager class which would effectively be the controller. Doing this would increase the reuse ability of my manager class.
interface IGetObjects
{
public object GetItem();
public object GetList();
}
class GetObjectsManager
{
private IGetObjects mGetObject;
public GetObjectsManager(IGetObjects GetObject)
{
this.mGetObject = GetObject;
}
public object GetItem()
{
return this.mGetObject.GetItem();
}
public object GetList()
{
return this.GetList();
}
}
I know I'd have to ditch passing in the parameters to the methods themselves and use class properties instead, but I'd lose the dependency injection. I know I'd have to cast the return objects at the calling code into what they're supposed to be. So my helper classes would then look like this:
class DatastoreHelper
{
public string DatastoreName { get; set; }
public string DatastoreID { get; set; }
public object GetItem()
{
// return new Datastore(); from somewhere
}
public List<object> GetList()
{
// return List<Datastore>(); from somewhere
}
}
class HostSystemHelper
{
public int HostSystemID { get; set; }
public string ClusterName {get; set;}
public object GetItem()
{
// return new HostSystem(); from somewhere
}
public List<object> GetList()
{
//return new List<HostSystem>(); from somewhere
}
}
But is the above a good idea or am I trying to fit a pattern in somewhere it doesn't belong?
EDIT: I've added some more overloaded methods to illustrate that my classes are complex and contain many methods, some overloaded many times according to different input params.
If I understand the concept correctly, a design like this is a really bad idea:
class DatastoreHelper
{
public string DatastoreName { get; set; }
public string DatastoreID { get; set; }
public object GetItem()
{
// return new Datastore(); from somewhere
}
public List<object> GetList()
{
// return List<Datastore>(); from somewhere
}
}
The reason is that getting results would now be a two-step process: first setting properties, then calling a method. This presents a whole array of problems:
Unintuitive (everyone is used to providing parameters as part of the method call)
Moves the parameter binding away from the call site (granted, this would probably mean "moves them to the previous LOC", but still)
It's no longer obvious which method uses which property values
Take an instance of this object and just add a few threads for instant fun
Suggestions:
Make both IGetObjects and GetObjectsManager generic so that you don't lose type safety. This loses you the ability to treat different managers polymorphically, but what is the point in that? Each manager will be in the end specialized for a specific type of object, and unless you know what that type is then you cannot really use the return value of the getter methods. So what do you stand to gain by being able to treat managers as "manager of unknown"?
Look into rewriting your GetX methods to accept an Expression<Func<T, bool>> instead of bare values. This way you can use lambda predicates which will make your code massively more flexible without really losing anything. For example:
helper.GetItem(i => i.DataStoreID == 42);
helper.GetList(i => i.DataStoreName.Contains("Foo"));
The first code samples look quite similar to the Repository Pattern. I think this is what are you trying to apply. The last sample is not good and Jon told you why. However, instead of reinventing the wheel, read a bit about the Repository (lots of questions about it on SO) because, if I understood correctly, this is what you really want.
About reuse, not many things and especially persistence interface are reusable. There is the Generic Repository Pattern (I consider it an anti-pattern) which tries to accomplish that but really, do all the application needs the same persistence interface?
As a general guideline, when you design an object, design it to fullfil the specific application needs, if it happens to be reused that's a bonus, but that's not a primary purpose of an object.
It is not a good idea. Based on these examples you would be better off with a generic interface for the varying return type and parameters of GetItem/GetList. Though honestly the prevalence of Managers, the use of something cas vague as GetItem in multiple places and trying to fit your solution into design patterns (rather than defining the solution in terms of the patterns) are huge code smells to me for the wider solution.

How do I convert one object to another?

I have an interface named IDeviceId that I use in my domain. I also have several concrete classes that implement IDeviceId. Each concrete class contains the logic for a specific type of DeviceId. For example, I have DeviceMacId, which is simply a valid MAC address. Another concrete class is DeviceShortMacId, which takes the last 6 digits of a valid MAC address and combines it with a fixed 6-character prefix to create a valid MAC (several legacy apps use only the last 6 digits). I have a few other classes for expressing an ID, but the majority of them are all derivatives of the same data.
I'd like to be able to easily convert from any one of these classes to another. My first thought was to create a static class and do something like DeviceIdConverter.ToDeviceShortMacId(IDeviceId).
What's the best way be able to easily accept data in one form, and then convert it to another in a repeatable fashion (across multiple apps)?
I don't think there is a "best way" to do this, you're going to have to find a pattern that works for you and go with it.
Off the top of my head, based on the examples you presented I would do something like:
interface IDeviceId
{
// Other methods
IDeviceId ToDeviceShortMacId(IDeviceId);
IDeviceId ToDeviceMacId(IDeviceId);
// etc...
}
Then each of the classes would need to implement the conversion methods. Now if you plan on adding a lot of other implementation (concrete) classes later, then this could get pretty verbose. So what you might consider in that case is in each of the projects which creates a new implementation you also create extension methods like:
public static class MacDeviceIdExtensions
{
public static DeviceMacId ToDeviceMacId(this IDeviceId deviceId)
{
// Implement conversion
}
public static DeviceShortMacId ToDeviceMacId(this IDeviceId deviceId)
{
// Implement conversion
}
}
The extension methods approach is a lot more modular, but could also be a lot more code.
One possibility would be to implement your own casting:
public static explicit operator DeviceShortMacId(DeviceMacId deviceMacID)
{
return new DeviceShortMacId(deviceMacID.MacAddress);
}
public static explicit operator DeviceMacId(DeviceShortMacId deviceShortMacID)
{
return new DeviceMacId(deviceShortMacID.MacAddress);
}
That way you can do:
DeviceMacId newDeviceId = (DeviceShortMacId)deviceMacID
With this approach, if some conversions are not possible, you can handle that yourself and throw an InvalidCastException.
Call me old fashioned, but I kind of like the static method approach here. You'll have the conversion logic decoupled from your entities, with a descriptive method name to describe what each conversion does. You might also want to consider implementing them as extension methods.
Why don't you just create constructors on all your IDeviceID implementing classes that accept an IDeviceID object.
DeviceMacID macID = new DeviceMacID(...whatever you do normally...);
DeviceShortMacID shortMacID = new DeviceShortMacID((IDeviceID)macID);
Example code
public DeviceShortMacID : IDeviceID
{
private ID _ID;
public DeviceShortMacID() { }
public DeviceShortMacID(IDeviceID id)
{
if (id is DeviceshortMacID)
this._ID = id.GetID();
else
this._ID = this.ConvertFrom(id);
}
public ID ConvertFrom(IDeviceID oldID) { ... convert code ...}
public ID GetID() { return this_ID; }
}
public interface IDeviceID
{
public ID GetID();
public ID ConvertFrom(IDeviceID oldID);
}
public class ID { } // I don't know what you return so I'm making up this class

C# virtual static method

Why is static virtual impossible? Is C# dependent or just don't have any sense in the OO world?
I know the concept has already been underlined but I did not find a simple answer to the previous question.
virtual means the method called will be chosen at run-time, depending on the dynamic type of the object. static means no object is necessary to call the method.
How do you propose to do both in the same method?
Eric Lippert has a blog post about this, and as usual with his posts, he covers the subject in great depth:
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/calling-static-methods-on-type-parameters-is-illegal-part-one
“virtual” and “static” are opposites! “virtual” means “determine the method to be called based on run time type information”, and “static” means “determine the method to be called solely based on compile time static analysis”
The contradiction between "static" and "virtual" is only a C# problem. If "static" were replaced by "class level", like in many other languages, no one would be blindfolded.
Too bad the choice of words made C# crippled in this respect. It is still possible to call the Type.InvokeMember method to simulate a call to a class level, virtual method. You just have to pass the method name as a string. No compile time check, no strong typing and no control that subclasses implement the method.
Some Delphi beauty:
type
TFormClass = class of TForm;
var
formClass: TFormClass;
myForm: TForm;
begin
...
formClass = GetAnyFormClassYouWouldLike;
myForm = formClass.Create(nil);
myForm.Show;
end
Guys who say that there is no sense in static virtual methods - if you don't understand how this could be possible, it does not mean that it is impossible. There are languages that allow this!! Look at Delphi, for example.
I'm going to be the one who naysays. What you are describing is not technically part of the language. Sorry. But it is possible to simulate it within the language.
Let's consider what you're asking for - you want a collection of methods that aren't attached to any particular object that can all be easily callable and replaceable at run time or compile time.
To me that sounds like what you really want is a singleton object with delegated methods.
Let's put together an example:
public interface ICurrencyWriter {
string Write(int i);
string Write(float f);
}
public class DelegatedCurrencyWriter : ICurrencyWriter {
public DelegatedCurrencyWriter()
{
IntWriter = i => i.ToString();
FloatWriter = f => f.ToString();
}
public string Write(int i) { return IntWriter(i); }
public string Write(float f) { return FloatWriter(f); }
public Func<int, string> IntWriter { get; set; }
public Func<float, string> FloatWriter { get; set; }
}
public class SingletonCurrencyWriter {
public static DelegatedCurrencyWriter Writer {
get {
if (_writer == null)
_writer = new DelegatedCurrencyWriter();
return _writer;
}
}
}
in use:
Console.WriteLine(SingletonCurrencyWriter.Writer.Write(400.0f); // 400.0
SingletonCurrencyWriter.Writer.FloatWriter = f => String.Format("{0} bucks and {1} little pennies.", (int)f, (int)(f * 100));
Console.WriteLine(SingletonCurrencyWriter.Writer.Write(400.0f); // 400 bucks and 0 little pennies
Given all this, we now have a singleton class that writes out currency values and I can change the behavior of it. I've basically defined the behavior convention at compile time and can now change the behavior at either compile time (in the constructor) or run time, which is, I believe the effect you're trying to get. If you want inheritance of behavior, you can do that to by implementing back chaining (ie, have the new method call the previous one).
That said, I don't especially recommend the example code above. For one, it isn't thread safe and there really isn't a lot in place to keep life sane. Global dependence on this kind of structure means global instability. This is one of the many ways that changeable behavior was implemented in the dim dark days of C: structs of function pointers, and in this case a single global struct.
Yes it is possible.
The most wanted use case for that is to have factories which can be "overriden"
In order to do this, you will have to rely on generic type parameters using the F-bounded polymorphism.
Example 1
Let's take a factory example:
class A: { public static A Create(int number) { return ... ;} }
class B: A { /* How to override the static Create method to return B? */}
You also want createB to be accessible and returning B objects in the B class. Or you might like A's static functions to be a library that should be extensible by B. Solution:
class A<T> where T: A<T> { public static T Create(int number) { return ...; } }
class B: A<B> { /* no create function */ }
B theb = B.Create(2); // Perfectly fine.
A thea = A.Create(0); // Here as well
Example 2 (advanced):
Let's define a static function to multiply matrices of values.
public abstract class Value<T> where T : Value<T> {
//This method is static but by subclassing T we can use virtual methods.
public static Matrix<T> MultiplyMatrix(Matrix<T> m1, Matrix<T> m2) {
return // Code to multiply two matrices using add and multiply;
}
public abstract T multiply(T other);
public abstract T add(T other);
public abstract T opposed();
public T minus(T other) {
return this.add(other.opposed());
}
}
// Abstract override
public abstract class Number<T> : Value<T> where T: Number<T> {
protected double real;
/// Note: The use of MultiplyMatrix returns a Matrix of Number here.
public Matrix<T> timesVector(List<T> vector) {
return MultiplyMatrix(new Matrix<T>() {this as T}, new Matrix<T>(vector));
}
}
public class ComplexNumber : Number<ComplexNumber> {
protected double imag;
/// Note: The use of MultiplyMatrix returns a Matrix of ComplexNumber here.
}
Now you can also use the static MultiplyMatrix method to return a matrix of complex numbers directly from ComplexNumber
Matrix<ComplexNumber> result = ComplexNumber.MultiplyMatrix(matrix1, matrix2);
While technically it's not possible to define a static virtual method, for all the reasons already pointed out here, you can functionally accomplish what I think you're trying using C# extension methods.
From Microsoft Docs:
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Check out Extension Methods (C# Programming Guide) for more details.
In .NET, virtual method dispatch is (roughly) done by looking at the actual type of an object when the method is called at runtime, and finding the most overriding method from the class's vtable. When calling on a static class, there is no object instance to check, and so no vtable to do the lookup on.
To summarize all the options presented:
This is not a part of C# because in it, static means "not bound to anything at runtime" as it has ever since C (and maybe earlier). static entities are bound to the declaring type (thus are able to access its other static entities), but only at compile time.
This is possible in other languages where a static equivalent (if needed at all) means "bound to a type object at runtime" instead. Examples include Delphi, Python, PHP.
This can be emulated in a number of ways which can be classified as:
Use runtime binding
Static methods with a singleton object or lookalike
Virtual method that returns the same for all instances
Redefined in a derived type to return a different result (constant or derived from static members of the redefining type)
Retrieves the type object from the instance
Use compile-time binding
Use a template that modifies the code for each derived type to access the same-named entities of that type, e.g. with the CRTP
The 2022+ answer, if you are running .Net 7 or above, is that now static virtual members is now supported in interfaces. Technically it's static abstract instead of "static virtual" but the effect is that same. Standard static methods signatures can be defined in an interface and implemented statically.
Here are a few examples on the usage and syntax in .Net 7

Categories