Click here to Skip to main content
15,905,028 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Why i can not override the static methods in c#

What I have tried:

I tried Overriding Static Method but i couldnt explain .
Posted
Updated 18-Jan-17 21:37pm

1 solution

You can't override static methods because the method isn't related to any specific instance of the class, but shared between all instances - so it can't be virtual.

What that means is that when you access a non-static method, you do it via an instance - in much the same way that you use "my car", "your car", "this car", or "that car" to specify a single individual vehicle from the "phase space" of all possible cars. Using that instance, you can ask questions, or get information:
What colour is your car?
What fuel does this car use?
You can't ask those questions without specifying a particular car because "what colour is a car?" is a ridiculous question - it doesn't have a single answer. But you can say "how many wheels has a car?" because by definition, all cars have four wheels - you don't need an instance to ask the question.
In C# terms, "how many wheels?" is a static method - you access it via the class name rather than via an instance. Which means you always call the same method - to call a static method of the same name in a derived class you would have to use the derived class name instead.
Non-static methods are different: they are accessed via the actual instance which can be of a class or a derived class - and the system can select the "highest" override of a method for the actual class of the instance when you try to access it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900