Alex Rivera | Logout

C# virtual static method

Asked 2009-08-07T09:31:40.713
38

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.

Edit
Report

3 Answers

53

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?

answered 2009-08-07T09:35:00.643
10

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
answered 2011-09-13T16:40:02.487
2

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.

answered 2009-08-07T12:35:27.697

Your Answer