Inheritance of class properties
-
I'm trying to figure out how to override the value of a propery for a parent class in a child class. For example, i have
public class Base { public virtual string _Caption="parentresult";} public class Child { public override string _Caption="childresult";}
But the "virtual" and "override" keywords raise errors during compilation("modifier not valid for this item). They work if I set them up accessor methods, but I shouldn't have to do that (should I?). Is it possible to make them consts, also? -
I'm trying to figure out how to override the value of a propery for a parent class in a child class. For example, i have
public class Base { public virtual string _Caption="parentresult";} public class Child { public override string _Caption="childresult";}
But the "virtual" and "override" keywords raise errors during compilation("modifier not valid for this item). They work if I set them up accessor methods, but I shouldn't have to do that (should I?). Is it possible to make them consts, also?redivider.geo, I think you can only override methods/properties and not variables. Also, your Child class does not inherit Base so it has nothing to override.
public class Base
{
private string _caption = "parentresult";
public virtual string Caption
{
get { return _caption; }
set { _caption = value; }
}
}public class Child : Base { public override string Caption { get { return base.Caption; } set { base.Caption = value; } } }
Regards, Gareth. (FKA gareth111)
-
I'm trying to figure out how to override the value of a propery for a parent class in a child class. For example, i have
public class Base { public virtual string _Caption="parentresult";} public class Child { public override string _Caption="childresult";}
But the "virtual" and "override" keywords raise errors during compilation("modifier not valid for this item). They work if I set them up accessor methods, but I shouldn't have to do that (should I?). Is it possible to make them consts, also?Variables can not be virtual. What you are doing is not overriding, it's shadowing. To tell the compiler that you intend to shadow the variable in the parent class, you use the new keyword:
public class Base {
public string _Caption="parentresult";
}public class Child : Base {
public new string _Caption="childresult";
}If you want to override something, it has to be a property or a method.
Despite everything, the person most likely to be fooling you next is yourself.