override static methods
-
Friday, March 03, 2006 2:16 AM
Very simple question. Why is it impossible to override static method in C#?
I would like to be able to do the following:
public
interface IParent{
object execute(object dataObject);}
class Child : IParent
{
public static override object execute(object dataObject){
return obj;
}
}
What should I use instead?
Thx
All Replies
-
Friday, March 03, 2006 3:33 AM
No you cannot override a static method.
from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfOverridePG.asp
You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
I am not quite following what it is you are trying to do here well enough to tell you how you should do it. Could you give a bit more concrete of an example because you also have the static method seemingly implementing an interface method.
-
Friday, March 03, 2006 4:07 PM
I have small business logic units that I call Transaction Scripts. These are nothing but classes with only one static method called execute. That method takes an object as a parameter and returns an object.
I would like to create a "Pattern" forcing other programmers who want to create a new Transaction Script to do it in a correct way.
Then, for every new Transaction Script created, if that "Pattern" is extended, I will be sure that the new class has a static execute method with the right signature.
-
Friday, March 03, 2006 8:02 PM
Static method are used when you need to access a method without the need to create an object of the class. So it does not really belong the that class.
Here is a good thread with some solution:
-
Friday, March 03, 2006 8:35 PM
It is interesting that you have chosen this name; it also happens to be an official pattern name for a very similar concept http://www.martinfowler.com/eaaCatalog/transactionScript.html:) One major difference you will see in the pattern is that instead of having a single object represent a single operation; the object will encapsulate multiple related functionalities.
As the_lotus points out the only difference between the static method and the instance method would be the need to instantiate the object. I would generally lean towards just instantiating the object.
Greg

