What is Interface Duck Typing? - c#

I heard the word Interface Duck Typing, but do not understand at all what is it? So I read a wiki about this and they said:
In computer programming with object-oriented programming languages, duck typing is a style of typing in which an object's methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of an explicit interface. The name of the concept refers to the duck test.
But still could not understand what it. So I saw their program but they use dynamic keyword to call quack() & feather() function of all the classes.
I would request you all please explain in easy way what is Interface Duck Typing and how to implement in C# v2.0 because there is no dynamic keyword.
using System;
namespace DuckTyping
{
public class Duck
{
public void Quack()
{
Console.WriteLine("Quaaaaaack!");
}
public void Feathers()
{
Console.WriteLine("The duck has white and gray feathers.");
}
}
public class Person
{
public void Quack()
{
Console.WriteLine("The person imitates a duck.");
}
public void Feathers()
{
Console.WriteLine("The person takes a feather from the ground and shows it.");
}
}
internal class Program
{
private static void InTheForest(dynamic duck)
{
duck.Quack();
duck.Feathers();
}
private static void Game()
{
Duck donald = new Duck();
Person john = new Person();
InTheForest(donald);
InTheForest(john);
}
private static void Main()
{
Game();
}
}
}

C# has a nominal type system, so the compatibility of types is done based on their names. In your example you have two classes with a Quack method, however there is no way to write a method which can take instances of these two classes and invoke their Quack method.
In C# 2, the solution would be to introduce an interface and have both classes implement it:
public interface IQuack
{
void Quack();
}
public class Duck : IQuack { }
public class Human : IQuack { }
now you can create a method which take an IQuack instance and can call Human.Quack and Duck.Quack through it. In C#, methods are resolved 'early' at compile time, so you need to create a named type which supports the operations the method need so the compilation can succeed. Note there is still a runtime element to calling these methods, since the real implementation of IQuack.Quack needs to be resolved at runtime depending on the real type of the argument.
In a duck-typing system, no attempt is made to validate that a method exists before runtime. All that is required is that a given object supports the operation in that it has the right name and takes the required number of parameters (none in this case), hence the 'if it quacks like a duck' expression.
Duck typing in C# 2 can only be done using reflection, in this case you would accept an object argument and look for the required methods yourself:
public static void MakeQuack(object duck)
{
MethodInfo quackMethod = duck.GetType().GetMethod("Quack", Type.EmptyTypes, null);
if (quackMethod!=null)
{
quackMethod.Invoke(duck, new object[] { });
}
else
{
throw new ArgumentException("No Quack() method found on target");
}
}
C#4 makes this much simpler with dynamic:
public static void MakeQuack(dynamic duck)
{
duck.Quack();
}

It would say it is a way of coding where the you tell the compiler:
"Hey trust me I know what methods and properties this object supports. You don't need to check them for me whilst I code."
Once you run your app the compiler will go:
"Ok lets see if I could trust you. Let me do some runtime binding."
If you then made a mistake, such as using an unsupported method, the compiler will shout: "Hey man, this is not supported! Check my RuntimeBinderException!"

Duck typing allows an object to be passed in to a method that expects
a certain type even if it doesn’t inherit from that type. All it has
to do is support the methods and properties of the expected type in
use by the method. I emphasize that last phrase for a reason. Suppose
we have a method that takes in a duck instance, and another method
that takes in a rabbit instance. In a dynamically typed language that
supports duck typing, I can pass in my object to the first method as
long as my object supports the methods and properties of duck in use
by that method. Likewise, I can pass my object into the second method
as long as it supports the methods and properties of rabbit called by
the second method. Is my object a duck or is it a rabbit? Like the
above image, it’s neither and it’s both. In many (if not most) dynamic
languages, my object does not have to support all methods and
properties of duck to be passed into a method that expects a duck.
Same goes for a method that expects a rabbit.It only needs to support
the methods and properties of the expected type that are actually
called by the method.
Please refer this to get an idea about Duck Typing
http://haacked.com/archive/2007/08/19/why-duck-typing-matters-to-c-developers.aspx/

About Duck Typing:
We don't need to know what the object is, but we just want to let the
object do something if it can do.
Example:
Example, if here are the things that we want the following objects do.
PleaseWalk(new Dog());
PleaseRun(new Duck());
PleaseWalk(new Cup());
PleaseFly(new Man());
PleaseFly(new Bird());
And, here is the result after we request the above objects do the things.
So, we don't need to check what the object is, but we can let it do something enough. Here is the code that I have written in C#.
private void PleaseWalk(object obj)
{
string Method = "Walk";
MethodInfo walkMethod = obj.GetType().GetMethod(Method, Type.EmptyTypes, null);
if (walkMethod != null)
{
walkMethod.Invoke(obj, new object[] { });
}
else
{
Console.WriteLine(string.Format("I can not {0} because {1}", Method, WhoAreYou(obj)));
}
}
private string WhoAreYou(object unknown)
{
MethodInfo whoAreYou = unknown.GetType().GetMethod("WhoAreYou", Type.EmptyTypes, null);
return whoAreYou.Invoke(unknown, new object[] { }).ToString();
}

You can use Events and exploit C# best suitable overload functions.
Hopefully, it will be useful :)
To get something Like a duck typing (.Net 4.+):
using System.Collections;
using System.Collections.Generic;
public interface IAny
{
void InvokeGetterEvent();
}
public class AnyValueTypeDuck<T, V> : IAny
where V : AnyValueTypeDuck<T, V>
{
public static event System.Action<V> GetterEvent;
public T Data;
public void InvokeGetterEvent()
{
GetterEvent.Invoke((V)this);
}
}
// Then create some concrete classes:
// Example :
public class LifeConcreteProperty : AnyValueTypeDuck<int, LifeConcreteProperty>
{
}
public class ManaConcreteProperty : AnyValueTypeDuck<float, ManaConcreteProperty>
{
}
// Now to finally use it :
public class UserClass
{
List<IAny> allDuckTypes = new List<IAny>();
public void GetDucketTypeClass(IAny anyDuckObject)
{
LifeConcreteProperty.GetterEvent += GetDucketType;
ManaConcreteProperty.GetterEvent += GetDucketType;
anyDuckObject.InvokeGetterEvent();
// it will propagate to event and will invoke
// best suitable overload method (GetDucketType)
LifeConcreteProperty.GetterEvent -= GetDucketType;
ManaConcreteProperty.GetterEvent -= GetDucketType;
}
public void GetDucketType(LifeConcreteProperty originalClass)
{
// Your efforts go here
int value = originalClass.Data;
}
public void GetDucketType(ManaConcreteProperty originalClass)
{
// Your efforts go here
float value = originalClass.Data;
}
}

Related

How to override a method in the instantion of an object in C#

I am a Java programmer trying to transition to C# and I'm hoping there's a way to do something in C# that I'm accustomed to in Java: overriding a method in the declaration of an abstract object like so:
//This is the way I do it in Java and want to do in C#
Keyword k = new Keyword("quit"){
public abstract void do(String context){
//TODO Do stuff
}
};
This is for some text game stuff I've been doing for a while in Java. I've looked into abstract and virtual and anonymous classes but none of them do exactly this. Abstract and virtual want me to create a whole new subclass, but this would be time consuming and unfeasible on a large scale. Anonymous classes don't (as far as I can tell) enable me to override methods, just fields and don't provide any stabilization for me to rely on.
If there is a way to do this or something similar please explain. Thanks for your time.
That doesn't work in C#. You'll have to create a new class that inherits from Keyword.
public class MyKeyword : Keyword
{
public MyKeyword(string s) : base(s)
{ }
public override void do(string context)
{
// TODO: Do stuff.
}
}
Anonymous Types in C# aren't classes that you can provide any public methods for. They only have properties, and are intended to be a quick, intra-method way of pasing complex data from one line to the next.
To be honest, I didn't know you could do what you show in Java. That is, if I'm understanding it as kind of an in-line class derivation.
Brian Rasmussen mentions using a delegate. That would look something like this:
public delegate void DoSomething(string context);
public class Keyword
{
public DoSomething Do;
private void CallsDo()
{
if (Do != null) Do("some string");
}
}
Then you can assign to it:
Keyword k = new Keyword();
k.Do = (ctx) => { /* Do something with ctx string */ };
Delegates are probably what you are after.
You can utilize a delegate for this approach: Note the example
public class Keyword
{
public delegate void Do();
}
//Area of Execution
{
//...
Keyword k = new Keyword();
k.Do = delegate()
{
Console.Writeln("Anonymous Inner function assigned to a callback function i.e a Delegate!");
};
}
These are much like function pointers in C/C++ but that may mean nothing to you depending on your background.
A delegate is, in the simplest terms, a type-safe object that encapsulates a method/function. What this means is that it maintains a reference to the method or methods and can invoke them later through the delegate object rather than explicitly on the method(s) themselves. You can assign an anonymous function to the right hand side much the same as you can to a method in Java as you described.
hope this helps. Read more here for delegates in-depth
Delegates

Syntax sugar for double-generic function

I have the following function in c#:
bool Handle<TCommandHandler, TModel>(TModel model) where TCommandHandler : ICommandHandler<TModel> {
// ...
_container.Resolve<TCommandHandler>();
// ...
}
Since TModel is clear from a function parameter I want some way to not specify its type when calling a function. Ideally I want to call it like:
Handle<MyCommandHandler>(model);
Since this is probably impossible, I came up with the following:
HandleTemp<TModel> Handle<TModel>(TModel model) {
return new HandleTemp<TModel>(model);
}
public class HandleTemp<TModel> {
private TModel _model;
public HandleTemp(TModel model) { _model = model;}
public bool With<TCommandHandler>() where TCommandHandler : ICommandHandler<TModel> {
}
}
So I'm now calling it like:
Handle(model).With<MyCommandHandler>();
Are there other possibilities? Did I make something completely wrong with my solution?
No, your analysis and solution look about right. Indeed, generic type inference can work only on an all-or-nothing basis. If there are some generic parameters that can't be inferred, all must be explicitly stated. Personally I'd quite like a way to say "you worry about these parameters, I'll tell you this one", but... that doesn't exist.
The only other option is to add an artificial extra regular parameter to allow it to infer the generic parameter - a bit yucky.
One other option: challenge the assumption that generics are needed here. For example, could it just be a Type instance? Would:
bool Handle<TModel>(TModel model, Type type)...
...
Handle(model, typeof(MyCommandHandler));
work, for example? I can't answer this directly, as I don't know the particulars of your _container.Resolve<TCommandHandler>(); method, as to whether that could be adjusted to take a Type rather than a <T>.
All the C# compiler needs is a demonstration of the type in the arguments, so instead of attempting to place it in the generic arguments (at the usage site) make something that lets you provide an argument that helps the compiler identify that type. To make it less confusing, here is an example:
// Your classes/interfaces.
class Container
{
public static T Resolve<T>()
{
Console.WriteLine("Resolving {0}", typeof(T).FullName);
return default(T);
}
}
interface ICommandHandler<TModel>
{
void DoSomething();
}
// An implemented ICommandHandler.
public class WackyCommandHandler : ICommandHandler<string>
{
public void DoSomething() { }
}
// Used to help the C# compiler identify types.
public static class Identify
{
public static TypeIdentity<TType> TheType<TType>()
{
return null; // You don't actually need an instance.
}
}
public sealed class TypeIdentity<TType>
{
private TypeIdentity() { }
}
// Your method
static bool Handle<TCommandHandler, TModel>(TModel model, TypeIdentity<TCommandHandler> handler)
where TCommandHandler : ICommandHandler<TModel>
{
var item = Container.Resolve<TCommandHandler>();
return true;
}
// And the usage site:
var a = "hello";
Handle(a, Identify.TheType<WackyCommandHandler>());
Console.ReadLine();

Can an interface be added to existing .NET types?

My example below involves 2 NET classes which both contain the method CommonMethod. I would like to design MyMethod that can accept either class (Using ) while retaining the functionality common to NetClassA and NetClassB. Case1 would do just that only it is illegal as stated below. Case2 would also accomplish the goal except INetClassA and INetClassB do not exist. Therefore my question is there a way to impose a custom interface (ICommonNetMethods) on existing .NET types (Case 3)? Alternative solutions to my problem are welcomed.
// Case 1: Illegal because "where" can only have 1 base class
public void MyMethod<Ttype>(Ttype myClass) where Ttype : NetClassA, NetClassB {}
// Case 2: Legal to utlize multiple "where" interface types
public void MyMethod<Ttype>(Ttype myClass) where Ttype : INetClassA, INetClassB {}
// Case 3: For this to work ICommonNetMethods must be added to NetClassA/NetClassB
public void MyMethod<Ttype>(Ttype myClass) where Ttype : ICommonNetMethods {}
NetClassA() { This .NET class has method CommonMethod() }
NetClassB() { This .NET class has method CommonMethod() }
interface ICommonNetMethods { void CommonMethod() }
Thanks,
aidesigner
There are ways to solve this that involve creative thinking.
Most obvious:
Adapter Pattern
You build your interface, then two adapters where each take NetClassA and the other NetClassB. Your common code stays common and the specific lives in the adapters.
This works even for sealed classes. You do not dervice from NetClassA or NetClassB. I kind of want to leave this to you to figure out the implementation, come back in a day if you want the code implementation I'll post it.
Other things to look at:
Extension Methods
and/or
Reflection
More Help
=====================
= ICommonNetMethods =
=====================
| (derive)
|-------------------------------|
==================== ====================
= NetClassAAdapter = = NetClassBAdapter =
==================== ====================
| uses (not derive) | uses (not derive)
============= =============
= NetClassA = = NetClassB =
============= =============
Use Func<>:
Assume two classes, A and B, each with a function Foo (though this isn't really a requirement for this solution, observe class C, below):
public class A { int Foo() { return 1; } }
public class B { int Foo() { return 2; } }
public class C { int Deviant() { return 3; } }
Then in some code fragment, you will write:
var a = new A();
var b = new B();
var c = new C();
var fs = new Func<int>[] {() => a.Foo(), () => b.Foo(), () => c.Deviant()};
So to use this:
foreach(var func in fs)
Console.WriteLine(func());
Which in turn will output:
1
2
3
Lambda functions are a big deal in C#, and a great technology to learn. If you are unfamiliar, and would like to learn more, start at Microsoft's help page.
If you are looking at larger interfaces, consider, as has been mentioned, the adapter pattern. If the idea of wrapping each of your objects with their own concrete adapter classes seems like too much bloat for your buck, then again, Func<> to the rescue.
public interface ISomeInterface
{
void f1();
int f2(string p1);
...
}
public class FuncImplementation : ISomeInterface
{
public Action Func_f1 { get; set; }
public Func<string,int> Func_f2 { get; set; }
...
public void f1() { Func_f1(); }
public int f2(string p1) { return Func_f2(p1); }
...
}
Now you can make new Adapters inline:
var adaptA = new FuncImplementation { Func_f1 = MyF1, Func_f2 = Myf2 };
adaptA.f1();
You cannot impose an interface on existing code (unless you use a code weaver like PostSharp, but that's cheating ;-).
Instead, consider these options:
If you simply have a single method on your interface, you could use
a Delegate instead.
You could make a simple wrapper class for each of your types, and implement the interface there.
C# 4.0 introduced the dynamic keyword which allows C# developers to use duck typing (an alternative to the adapter pattern). With it, you could define MyMethod like this:
public void MyMethod(dynamic myClass)
{
myClass.CommonMethod();
}
You could then simply pass instances of NetClassA and NetClassB to MyMethod like this:
var a = new NetClassA();
var b = new NetClassB();
MyMethod(a);
MyMethod(b);
The drawback to this approach is that there's no static type checking. If NetClassA or NetClassB didn't have a method called CommonMethod that accepted no parameters, the program would compile, but fail at run time.
Also since there's no associated interface, it's not clear what functions and properties are available. Avoid using this approach in public facing assemblies.
The only way I can think of (off the top of my head) is to derive from the .NET class in question and add your interface to that implementation. I don't think that's the optimal solution, however.
Why not simply inspect the type that Ttype is in the method, and execute your code accordingly based on the type?
For example:
public void MyMethod<Ttype>(Ttype myClass)
{
string className = typeof(Ttype).Name;
switch (className)
{
case "NetClassA":
// Do stuff
break;
case "NetClassB":
// Do stuff
break;
default:
// Do something if necessary
break;
}
}
Thanks to all, I was really impressed with the various options. First I had already started pursing the delegate option ( The use of nested type parameters and recursion (C#) ) and have an almost ideal solution. The second post on this thread shows my exact implementation. This approach tries to solve the problem by passing just the needed function "Add" of NETClassA (SrgsItem) and NetClassB (SrgsElement) instead of the entire class. This is almost perfect except C# lack of "Generics Variance" support is getting in the way.
As to the other options they are all very insightful. After pursuing the delegate thread I will be trying the Adapter/Func approach proposed by Michael and Andrew (Will add comments). If you have time please follow the delegate thread above as it relates and it might help understand another facet of C#.
As of 2022, the best practice of C# is still to map external classes into Value Objects or Adaptors. To some people such as me, this is a logic overhead I wish to remove.
C# type system is closed in that we cannot extend an existing class with new interfaces. Of course, this can be mitigated by using a New-type Pattern.
class ExternalClass {
public string InfoWithDifferentLayoutOrName { get; }
}
interface IMyInterface {
string Info { get; }
}
record struct ExternalClassExtensionWrapper(ExternalClass Value): IMyInterface {
public string Info => Value.InfoWithDifferentLayoutOrName;
}
T MyAwesomeInnerFunc<T>(T input) where T: IMyInterface { ... }
But, from the view of code design, this approach does not cut down on code logic compared to a value-object mapper as you still have to write something like a wrapper. The only difference is whether you are depending on a concrete layout (VOs) or a contract (interfaces). A mysophobia do exist in the wild that insists interfaces bring lower coupling, but I don't see any lower cognitive burden in this specific case.
You will like a trait system where you can extend interfaces on others.

How do I cast an object to its own type?

I've read several posts on this problem but none of the answers seem to work for me. Here is the situation--I have a generic function to call in another class:
public class Dispatcher<T> where T : Event {
public void Notify<X>(X tEvent) where X : Event {
if (someField is IListener<X, T>) {
//this never executes--X is Event regardless of its derived type
}
}
}
and the calling code:
public class Effect {
public Event myEvent;
public CallNotify() {
Dispatcher.Notify(myEvent);
}
}
The problem is that Event has dozens of derived types, and I need the Notify() call to happen with the derived type as X. So far, it just calls Notify< Event >() no matter what kind of Event I pass in. The only solution that compiles is to call Notify(myEvent as DerivedEvent), but that has to be hardcoded for every single type--not acceptable.
A similar function infers properly if I give it a "this" pointer from an instance of the derived class.
Surely there's a solution using Reflection here.
In order to call it as you seem to expect you would have to use reflection to generate a method of the actual type of myEvent. But I would stress that doing the following is a BAD idea and probably means your design needs to be rethought out.
MethodInfo openGenericMethod = OtherClass.GetType().GetMethod("Notify");
MethodInfo closedGenericMethod = openGenericMethod.MakeGenericMethod(myEvent.GetType());
closedGenericMethod.Invoke(OtherClass, new object[]{ myEvent });,
I didn't actually test the above code, but it would look something like that
You've got two issues.
First, your generics are leaking. Whenever you need to determine what type a particular instance is, your function is no longer generic. Consider your design flawed and re-examine what you are trying to do.
Second, IListener<X,Y> is not a type. Generics aren't generic in .NET; the runtime determines all actual types your application will require and creates them. The runtim will create, for example, a type IListener<int,string> if you actually use that in your application.
var foo = new List<int>();
var bar = foo.GetType() == typeof(List<>);
In this examle, bar is false.
Even with all this, yes, it is possible. You just have to understand how reflection with generic type definitions works. This is a pretty good link at MSDN that explains how it works.
I would strongly suggest that you reconsider using generics in this manner. Sometimes abstraction ad absurdum isn't the best thing...
Could you just drop the constraint and check to make sure it derives from Event, like this:
public class Dispatcher<T> where T : Event {
public void Notify<X>(X tEvent) {
if(typeof(tEvent).IsSubclassOf(typeof(Event))
{
if (someField is IListener<X, T>) {
//this never executes--X is Event regardless of its derived type
}
}
}
}
So I seem to have figured out a workaround on the other end. Instead of
public class Dispatcher<T> where T : Event {
public void Notify<X>(X tEvent) where X : Event {
foreach (Object l in listeners) {
if (l is IListener<X, T>) { //never true
(l as IListener<X, T>).OnEvent();
}
}
}
}
I have this mishmash:
public class Dispatcher<T> where T : Event {
public void Notify<X>(X tEvent) where X : Event {
foreach (Object l in listeners) {
foreach (Type t in l.GetType().GetInterfaces()) {
Type[] temp = t.GetGenericArguments();
if (temp.Count() > 0 && temp[0] == tEvent.GetType()) {
MethodInfo mi = t.GetMethod("OnEvent", new Type[] {tEvent.GetType()});
mi.Invoke(l, new object[] { tEvent });
}
}
}
}
}
This seems to work although I don't like having to test every interface (Windows Forms have at least 10 interfaces). I'm going to try the solution from BrandonAGr

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