I have read through the follow SO articles
All seem very close to my question and have good answers, but they do not seem to answer my question other than to say that I need to make the method non-static.
an example:
abstract public class baseClass
{
private static List<string> attributeNames = new List(new string {"property1","property2"});
// code for property definition and access
virtual public static bool ValidAttribtue(string attributeName)
{
if (attributeNames.Contains(attributeName))
return true;
else
return false;
}
}
class derivedA : baseClass
{
private static List<string> attributeNames = new List(new string {"property3","property4"});
// code for property definition and access
public static override bool ValidAttribute(string attributeName)
{
if (attributeNames.Contains(attributeName))
{
return true;
}
else
{
return base.ValidAttribute(attributeName);
}
}
}
class derivedB : baseClass
{
private static List<string> attributeNames = new List(new string {"property10","property11"});
// code for property definition and access
public static override bool ValidAttribute(string attributeName)
{
if (attributeNames.Contains(attributeName))
{
return true;
}
else
{
return base.ValidAttribute(attributeName);
}
}
}
derivedA would have properties 1,2,3,4 while derivedB would have properties 1,2,10,11. The list of properties seems to be a class specific value and can not be changed at any point. I would think it then would be static.
Is my design wrong in the sense that I am trying to use static methods when they should not be?
The above example makes me think that inheritance of static methods would be needed, yet it seems that trying to do this is a design flaw. Can anyone help me to understand what is wrong with coding or structuring classes in this manner?
Is my design wrong in the sense that I am trying to use static methods when they should not be?
Yes. Aside from anything else, you're trying to declare a static method as virtual
(and then override it), which isn't allowed. You're also trying to declare a class called base
, when that's a keyword.
Static methods simply aren't polymorphic. The basis of polymorphism is that the execution time type of the instance involved can be different to the compile-time type of the expression, and the implementation is chosen on the basis of the execution time type. That concept doesn't make sense for static methods as there is no instance.
Now of course you can make a static method in a derived class call a static method in the base class - but there won't be any polymorphism anywhere.
As a side note, all of your methods could be written in a more readable way:
// Base class implementation
return attributeNames.Contains(attributeName);
// Derived class implementations
return attributeNames.Contains(attributeName) ||
BaseClass.ValidAttribute(attributeName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With