I have an abstract base class and I want to declare a field or a property that will have a different value in each class that inherits from this parent class.
I want to define it in the baseclass so I can reference it in a base class method - for example overriding ToString to say "This object is of type property/field".
I have got three ways that I can see of doing this, but I was wondering - what is the best or accepted way of doing this? Newbie question, sorry.
Option 1:
Use an abstract Property and override it on the inherited classes. This benefits from being enforced (you have to override it) and it is clean. But, it feels slightly wrong to return a hard-code value rather than encapsulate a field and it is a few lines of code instead of just. I also have to declare a body for "set" but that is less important (and there is probably a way to avoid that which I am not aware of).
abstract class Father
{
abstract public int MyInt { get; set;}
}
class Son : Father
{
public override int MyInt
{
get { return 1; }
set { }
}
}
Option 2
I can declare a public field (or a protected field) and explicitly override it in the inherited class. The example below will give me a warning to use "new" and I can probably do that, but it feels wrong and it breaks the polymorphism, which was the whole point. Doesn't seem like a good idea...
abstract class Mother
{
public int MyInt = 0;
}
class Daughter : Mother
{
public int MyInt = 1;
}
Option 3
I can use a protected field and set the value in the constructor. This seems pretty tidy but relies on me ensuring the constructor always sets this and with multiple overloaded constructors there is always a chance some code path won't set the value.
abstract class Aunt
{
protected int MyInt;
}
class Niece : Aunt
{
public Niece()
{
MyInt = 1;
}
}
It's a bit of a theoretical question and I guess the answer has to be option 1 as it is the only safe option but I am just getting to grips with C# and wanted to ask this of people with more experience.
Of the three solutions only Option 1 is polymorphic.
Fields by themselves cannot be overridden. Which is exactly why Option 2 returns the new keyword warning.
The solution to the warning is not to append the “new” keyword, but to implement Option 1.
If you need your field to be polymorphic you need to wrap it in a Property.
Option 3 is OK if you don’t need polymorphic behavior. You should remember though, that when at runtime the property MyInt is accessed, the derived class has no control on the value returned. The base class by itself is capable of returning this value.
This is how a truly polymorphic implementation of your property might look, allowing the derived classes to be in control.
abstract class Parent
{
abstract public int MyInt { get; }
}
class Father : Parent
{
public override int MyInt
{
get { /* Apply formula "X" and return a value */ }
}
}
class Mother : Parent
{
public override int MyInt
{
get { /* Apply formula "Y" and return a value */ }
}
}
Option 2 is a non-starter - you can't override fields, you can only hide them.
Personally, I'd go for option 1 every time. I try to keep fields private at all times. That's if you really need to be able to override the property at all, of course. Another option is to have a read-only property in the base class which is set from a constructor parameter:
abstract class Mother
{
private readonly int myInt;
public int MyInt { get { return myInt; } }
protected Mother(int myInt)
{
this.myInt = myInt;
}
}
class Daughter : Mother
{
public Daughter() : base(1)
{
}
}
That's probably the most appropriate approach if the value doesn't change over the lifetime of the instance.
You could do this
class x
{
private int _myInt;
public virtual int myInt { get { return _myInt; } set { _myInt = value; } }
}
class y : x
{
private int _myYInt;
public override int myInt { get { return _myYInt; } set { _myYInt = value; } }
}
virtual lets you get a property a body that does something and still lets sub-classes override it.
option 2 is a bad idea. It will result in something called shadowing; Basically you have two different "MyInt" members, one in the mother, and the other in the daughter. The problem with this, is that methods that are implemented in the mother will reference the mother's "MyInt" while methods implemented in the daughter will reference the daughter's "MyInt". this can cause some serious readability issues, and confusion later down the line.
Personally, I think the best option is 3; because it provides a clear centralized value, and can be referenced internally by children without the hassle of defining their own fields -- which is the problem with option 1.
You could define something like this:
abstract class Father
{
//Do you need it public?
protected readonly int MyInt;
}
class Son : Father
{
public Son()
{
MyInt = 1;
}
}
By setting the value as readonly, it ensures that the value for that class remains unchanged for the lifetime of the object.
I suppose the next question is: why do you need it?
If you are building a class and you want there to be a base value for the property, then use the virtual keyword in the base class. This allows you to optionally override the property.
Using your example above:
//you may want to also use interfaces.
interface IFather
{
int MyInt { get; set; }
}
public class Father : IFather
{
//defaulting the value of this property to 1
private int myInt = 1;
public virtual int MyInt
{
get { return myInt; }
set { myInt = value; }
}
}
public class Son : Father
{
public override int MyInt
{
get {
//demonstrating that you can access base.properties
//this will return 1 from the base class
int baseInt = base.MyInt;
//add 1 and return new value
return baseInt + 1;
}
set
{
//sets the value of the property
base.MyInt = value;
}
}
}
In a program:
Son son = new Son();
//son.MyInt will equal 2
You can go with option 3 if you modify your abstract base class to require the property value in the constructor, you won't miss any paths. I'd really consider this option.
abstract class Aunt
{
protected int MyInt;
protected Aunt(int myInt)
{
MyInt = myInt;
}
}
Of course, you then still have the option of making the field private and then, depending on the need, exposing a protected or public property getter.
I'd go with option 3, but have an abstract setMyInt method that subclasses are forced to implement. This way you won't have the problem of a derived class forgetting to set it in the constructor.
abstract class Base
{
protected int myInt;
protected abstract void setMyInt();
}
class Derived : Base
{
override protected void setMyInt()
{
myInt = 3;
}
}
By the way, with option one, if you don't specify set; in your abstract base class property, the derived class won't have to implement it.
abstract class Father
{
abstract public int MyInt { get; }
}
class Son : Father
{
public override int MyInt
{
get { return 1; }
}
}
I did this...
namespace Core.Text.Menus
{
public abstract class AbstractBaseClass
{
public string SELECT_MODEL;
public string BROWSE_RECORDS;
public string SETUP;
}
}
namespace Core.Text.Menus
{
public class English : AbstractBaseClass
{
public English()
{
base.SELECT_MODEL = "Select Model";
base.BROWSE_RECORDS = "Browse Measurements";
base.SETUP = "Setup Instrument";
}
}
}
This way you can still use fields.
The example implementation when you want to have an abstract class with implementation. Subclasses must:
Parameterize the implementation of an abstract class.
Fully inherit the implementation of the abstract class;
Have your own implementation.
In this case, the properties that are necessary for the implementation should not be available for use except for the abstract class and its own subclass.
internal abstract class AbstractClass
{
//Properties for parameterization from concrete class
protected abstract string Param1 { get; }
protected abstract string Param2 { get; }
//Internal fields need for manage state of object
private string var1;
private string var2;
internal AbstractClass(string _var1, string _var2)
{
this.var1 = _var1;
this.var2 = _var2;
}
internal void CalcResult()
{
//The result calculation uses Param1, Param2, var1, var2;
}
}
internal class ConcreteClassFirst : AbstractClass
{
private string param1;
private string param2;
protected override string Param1 { get { return param1; } }
protected override string Param2 { get { return param2; } }
public ConcreteClassFirst(string _var1, string _var2) : base(_var1, _var2) { }
internal void CalcParams()
{
//The calculation param1 and param2
}
}
internal class ConcreteClassSecond : AbstractClass
{
private string param1;
private string param2;
protected override string Param1 { get { return param1; } }
protected override string Param2 { get { return param2; } }
public ConcreteClassSecond(string _var1, string _var2) : base(_var1, _var2) { }
internal void CalcParams()
{
//The calculation param1 and param2
}
}
static void Main(string[] args)
{
string var1_1 = "val1_1";
string var1_2 = "val1_2";
ConcreteClassFirst concreteClassFirst = new ConcreteClassFirst(var1_1, var1_2);
concreteClassFirst.CalcParams();
concreteClassFirst.CalcResult();
string var2_1 = "val2_1";
string var2_2 = "val2_2";
ConcreteClassSecond concreteClassSecond = new ConcreteClassSecond(var2_1, var2_2);
concreteClassSecond.CalcParams();
concreteClassSecond.CalcResult();
//Param1 and Param2 are not visible in main method
}
Related
If I have a very simple class like so:
public class Example
{
public int Number { get; set; }
public Example(int numberArg)
{
this.Number = numberArg;
}
}
And I have a derivative class like so:
public class AnotherExample : Example
{
public int DoubleNumber
{
get
{
return this.Number * 2;
}
}
public AnotherExample(int numberArg) : base(numberArg) {}
}
What difference is there, if any, if I use this.Number to refer to the AnotherExample objects base Number property than if I use base.Number to refer to it?
Thanks!
If Number is not overridden there is no difference, as this.Number will resolve correctly in the chain of inheritance.
This also means that calling this.Member in a base class, if overridden in a derived class will again use the inheritance chain and find the derived implementation.
If it has been overridden, using base will always go to the base class's version of that property, whereas this.Number will first go to your overridden version.
If you plan on calling virtual members inside your constructors, please be aware of the general advice around it:
Virtual member call in a constructor
This answer is leaving out the explanation about member hiding as the OP example is simpler than that.
In this case, there is no difference. In case you override it will take the value from the base class instead of the inherited class:
public class Example {
public virtual int Number { get; set; }
public Example(int numberArg) {
this.Number = numberArg;
}
}
public class AnotherExample : Example {
public override int Number
{
get{return 5;}
set{}
}
public int DoubleNumber {
get {
return this.Number * 2; // returns 10
return base.Number * 2 // returns 2 times whatever the value is
}
}
public AnotherExample(int numberArg) : base(numberArg) {}
}
You can have a variable in derived class that has the same name with in the base class.In this case you need to use this and base keywords to avoid ambiguity.For example:
public class Base
{
public int Number = 0;
}
public class Derived : Base
{
public int Number;
public Derived()
{
this.Number = base.Number + 5;
}
}
I want to hide the base public property(a data member) in my derived class:
class Program
{
static void Main(string[] args)
{
b obj = new b();
obj.item1 = 4;// should show an error but it doent ???
}
}
class a
{
public int item1 {get; set;}
public int item2 { get; set; }
}
class b : a
{
new private int item1;
}
class c : a
{
}
i have member as public because i want the member to be inherited in c class , but want to hide the member in b class , how can i do this ?
dont i have an option to selectively inherite the variable i want in my base class ??? thats really bad , i think ms should provide us with an option (may be a modifier) to perform this
Edit:
I found the answer myself (i heard lots of them telling this is not possible in c#, but you can kind of do it)
I am including the code in case it is useful
class Program
{
static void Main(string[] args)
{
b obj = new b();
obj.item1 = 4; // shows an error : )
}
}
class a
{
public int item1 { get; set; }
public int item2 { get; set; }
}
class b : a
{
new public static int item1
{
get;
private set;
}
}
I'm going to attempt to explain with examples why this is a bad idea, rather than using cryptic terms.
Your proposal would be to have code that looks like this:
public class Base
{
public int Item1 { get; set; }
public int Item2 { get; set; }
}
public class WithHidden : Base
{
hide Item1; // Assuming some new feature "hide" in C#
}
public class WithoutHidden : Base { }
This would then make the following code invalid:
WithHidden a = new WithHidden();
a.Item1 = 10; // Invalid - cannot access property Item1
int i = a.Item1; // Invalid - cannot access property Item1
And that would be just what you wanted. However, suppose we now have the following code:
Base withHidden = new WithHidden();
Base withoutHidden = new WithoutHidden();
SetItem1(withHidden);
SetItem1(withoutHidden);
public void SetItem1(Base base)
{
base.Item1 = 10;
}
The compiler doesn't know what runtime type the argument base in SetItem1 will be, only that it is at least of type Base (or some type derived from Base, but it can't tell which -- it may be obvious looking at the code snippet, but more complex scenarios make it practically impossible).
So the compiler will not, in a large percentage of the cases, be able to give a compiler error that Item1 is in fact inaccessible. So that leaves the possibility of a runtime check. When you try and set Item1 on an object which is in fact of type WithHidden it would throw an exception.
Now accessing any member, any property on any non-sealed class (which is most of them) may throw an exception because it was actually a derived class which hid the member. Any library which exposes any non-sealed types would have to write defensive code when accessing any member just because someone may have hidden it.
A potential solution to this is to write the feature such that only members which declare themselves hideable can be hidden. The compiler would then disallow any access to the hidden member on variables of that type (compile time), and also include runtime checks so that a FieldAccessException is thrown if it is cast to the base type and tried to be accessed from that (runtime).
But even if the C# developers did go to the huge trouble and expense of this feature (remember, features are expensive, especially in language design) defensive code still has to be written to avoid the problems of potential FieldAccessExceptions being thrown, so what advantage over reorganising your inheritance hierarchy have you gained? With the new member hiding feature there would be a huge number of potential places for bugs to creep into your application and libraries, increasing development and testing time.
What you want to do goes directly against the grain of OO, you can't 'unpublish' members as this violates the substitution principle. You have to refactor this into something else.
Vadim's response reminded me of how MS achieve this in the Framework in certain places. The general strategy is to hide the member from Intellisense using the EditorBrowsable attribute. (N.B. This only hides it if it is in another assembly) Whilst it does not stop anyone from using the attribute, and they can see it if they cast to the base type (see my previous explination) it makes it far less discoverable as it doesn't appear in Intellisense and keeps the interface of the class clean.
It should be used sparingly though, only when other options like restructuring the inheritance hierarchy would make it a lot more complex. It's a last resort rather than the first solution to think of.
If you use an interface instead of a base class for defining the property, you could implement the property explicitly. The would require an explicit cast to the interface to use the property.
public interface IMyInterface
{
string Name { get; set; }
}
public class MyClass : IMyInterface
{
string IMyInterface.Name { get; set; }
}
You can find more out here.
The only thing I can think of is to make item1 virtual in class a:
class a
{
public virtual int item1 { get; set; }
public int item2 { get; set; }
}
and then override it in class b but throw an exception in getter and setter. Also if this property is used in a visual designer you can use Browsable attribute to not display.
class b : a
{
[Browsable(false)]
public override int item1
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
}
First of all this is not good idea if you using some methods, that operates base class.
You can try to use obsolete argument to make users twice think to use this property.
[System.Obsolete("Do not use this property",true)]
public override YourType YourProperty { get; set; }
What you are describing is something akin to 'private inheritance' from C++, and is not available in C#.
You cant do it directly, but you could override the properties in the child class and make them readonly e.g.
class Program
{
static void Main(string[] args)
{
b obj = new b();
obj.item1 = 4;// should show an error but it doent ???
}
}
class a
{
public virtual int item1 {get; set;}
public virtual int item2 { get; set; }
}
class b : a
{
public override int item1
{
get { return base.item1; }
set { }
}
}
class c : a
{
}
You could use interfaces to hide the property. The child class would implemented an interface that didn't have the property then it wouldn't appear.
You would need two interfaces for when you want the property and when you don't, thus making it a horrible hack.
You can override it and then Add a [Browsable(false)] tag to prevent showing it in designer.
Simple:
public class a:TextBox
{
[Browsable(false)]
public override string Text
{
get { return ""; }
set { }
}
}
Changing the accessibility of a virtual member is an inheriting class is specifically prohibited by the C# language spec:
The override declaration and the overridden base method have the same
declared accessibility. In other words, an override declaration cannot
change the accessibility of the virtual method. However, if the
overridden base method is protected internal and it is declared in a
different assembly than the assembly containing the override method
then the override method’s declared accessibility must be protected.
From section 10.6.4 Override methods
The same rules which apply to overriding method also apply to properties, so going from public to private by inheriting from the base class can't be done in C#.
What you actually need are interfaces:
public interface ProvidesItem1
{
int item1 { get; set; }
}
public interface ProvidesItem2
{
int item2 { get; set; }
}
class a : ProvidesItem1, ProvidesItem2
{
public int item1 { get; set; }
public int item2 { get; set; }
}
class b : ProvidesItem1
{
public int item1 { get; set; }
}
Then just pass the interfaces around. If the classes should use a common implementation, put that in a third class and let them derive from that class aswell as implement their respective interface.
Yes, it is possible. What say you on the delegation. I will try to give an idea of what is called "delegation" in OOP with a piece of code:
public class ClassA
{
// public
public virtual int MyProperty { get; set; }
// protected
protected virtual int MyProperty2 { get; set; }
}
public class ClassB
{
protected ClassC MyClassC;
public ClassB()
{
MyClassC = new ClassC();
}
protected int MyProperty2
{
get { return MyClassC.MyProperty2; }
set { MyClassC.MyProperty2 = value; }
}
protected int MyProperty
{
get { return MyClassC.MyProperty; }
set { MyClassC.MyProperty = value; }
}
protected class ClassC : ClassA
{
public new int MyProperty2
{
get { return base.MyProperty2; }
set { base.MyProperty2 = value; }
}
public override int MyProperty
{
get { return base.MyProperty; }
set { base.MyProperty = value; }
}
}
}
namespace PropertyTest
{
class a
{
int nVal;
public virtual int PropVal
{
get
{
return nVal;
}
set
{
nVal = value;
}
}
}
class b : a
{
public new int PropVal
{
get
{
return base.PropVal;
}
}
}
class Program
{
static void Main(string[] args)
{
a objA = new a();
objA.PropVal = 1;
Console.WriteLine(objA.PropVal);
b objB = new b();
objB.PropVal = 10; // ERROR! Can't set PropVal using B class obj.
Console.Read();
}
}
}
You can user new modifer.
Sample;
public class Duck
{
public string Color{get; set;}
public void Swim() { }
}
public class DonaldDuck : Duck
{
new public void Swim()
{
/*you could call in DonaldDuck.Swim only here but not public for DonaldDuck client.*/
}
}
If you wanna hide a member from base class then you will need to add a new base class let's call it baseA and your code should be as follows:
class Program
{
static void Main(string[] args)
{
b obj = new b();
obj.item1 = 4;// should show an error but it doent ???
}
}
class baseA
{
public int item2 { get; set; }
}
class a:baseA
{
public int item1 { get; set; }
}
class b : baseA { }
class c : a { }
I have an interface for a base class, and every class that inherits from the base class should have an identifying field which tells the application what kind of object it is.
I wanted to use this property in two different ways:
Without creating an instance of the object
if (someValue == TestA.Id)
return new TestA();
elseif (someValue == TestB.Id)
return new TestB();
And as a property of the interface
void DoSomething(ITest testObject)
{
SomeValue = testObject.Id;
}
Is there an easy way to define the Id field in the interface, but still have it available to use without creating an instance of the class?
Right now I am using the following code. I could add a read-only Id property to the interface which returns the const string, however I was hoping there was a simpler way that I'm just not aware of.
public interface ITest
{
}
public class TestA : ITest
{
public const string Id = "A";
}
In short - no.
In order to be able to do this, you'd need to be able to specify this as a instance property on the interface (and implement it in the instance), and as a static property on the type.
The compiler won't let you do this.
You can put it in the interface, and also have it as a static property. Something like:
interface IInterface { Id { get; } }
class Class : IInterface
{
public static Id { get { return 1; } }
public Id { get { return Class.Id; } }
}
I've faced a similar problem, Rachel, and I've always (unfortunately) resorted to having that factory code rely on reflection to get a "TypeID" public static property on each concrete type... thus making an additional aspect of the contractual interface, but not having it in the C# interface code.
You could do it this way.
public interface ITest
{
SomeValue Id{ get;}
}
public class TestA : ITest
{
public SomeValue Id
{
get {return TestA.StaicId; }
}
public static SomeValue StaticId
{
get {return "This is TestA";}
}
}
if (someValue == TestA.StaticId)
return new TestA();
How about using attributes? Here's a small example of what can be done:
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class IdAttribute : Attribute
{
public IdAttribute(string id)
{
this.Id = id;
}
public string Id { get; set; }
}
public interface IMyInterface
{
}
public abstract class BaseClass : IMyInterface
{
public static string GetId<T>() where T : IMyInterface
{
return ((IdAttribute)typeof(T).GetCustomAttributes(typeof(IdAttribute), true)[0]).Id;
}
}
[Id("A")]
public class ImplA : BaseClass
{
}
[Id("B")]
public class ImplB : BaseClass
{
}
internal class Program
{
private static void Main(string[] args)
{
var val1 = BaseClass.GetId<ImplA>();
var val2 = BaseClass.GetId<ImplB>();
Console.ReadKey();
}
}
I have a need where I have to add some new fields to an existing class along with all its existing fields/attributes.
So whenever my derived class is filled by DAL, I will be filling all fields of base class as well. Currently, I am doing it like this but not sure this is the right way ? Please give me an example. Also I am not sure whether the base class object will be a new one each time a derived class is initialized ?
public class Employee
{
private int _id;
private int _name;
public int ID
{
set { _id=value;}
get { return _id;}
}
public int Name
{
set { _name=value;}
get { return _name;}
}
protected void SetName ()
{
_name=value;
}
protected void SetID()
{
_id=value;
}
}
public class EmployeeWithDepartmentName:Employee
{
private string _deptName;
public string DeptName
{
set { _deptName=value; }
}
public setBaseEmpName()
{
base.SetName();
}
public setBaseID()
{
base.SetID();
}
}
Everything in a base class can automagically be accessed from derived classes without doiing anything, just use the property/method name directly.
public class MyBase
{
public string UserName {get;set;}
}
public class MyClass : MyBase
{
public void DoSomething()
{
Console.WriteLine("UserName: {0}", UserName);
UserName = "Anders";
}
}
You can also do this:
MyClass myClass = new MyClass();
myClass.UserName = "Rune";
Protected means that only derived classes can access the property/method. Public means that everyone can access the properties/methods.
Also I am not sure whether the base class object will be a new one each time a derived class is initialized ?
It's not two objects, it's one object created from two different classes (that's how inheritance works).
Read this article about inheritance: http://www.csharp-station.com/Tutorials/lesson08.aspx
I have an abstract class that defines a get, but not set, because as far as that abstract class is concerned, it needs only a get.
public abstract BaseClass
{
public abstract double MyPop
{get;}
}
However, in some of the derive class, I need a set property, so I am looking at this implementation
public class DClass: BaseClass
{
public override double MyPop
{get;set;}
}
The problem is, I got a compilation error, saying that
*.set: cannot override because *. does not have an overridable set accessor.
Even though I think that the above syntax is perfectly legitimate.
Any idea on this? Workaround, or why this is so?
Edit: The only approach I can think of is to put both get and set as in the abstract class, and let the subclass throws a NotImplementedException if set is called and it's not necessary. That's something I don't like, along with a special setter method .
One possible answer would be to override the getter, and then to implement a separate setter method. If you don't want the property setter to be defined in the base, you don't have many other options.
public override double MyPop
{
get { return _myPop; }
}
public void SetMyPop(double value)
{
_myPop = value;
}
New in C# 6.0:
If you are only calling the setter within your constructor, you can resolve this problem using read-only properties.
void Main()
{
BaseClass demo = new DClass(3.6);
}
public abstract class BaseClass
{
public abstract double MyPop{ get; }
}
public class DClass : BaseClass
{
public override double MyPop { get; }
public DClass(double myPop) { MyPop = myPop;}
}
It is not possible to do what you want. You have to define the setter in the abstract property, otherwise you won't be able to override it properly.
The only case I know where a getter is defined and a getter/setter are implemented is by using an interface:
public interface IBaseInterface
{
double MyPop { get; }
}
public class DClass : IBaseInterface
{
public double MyPop { get; set; }
}
If BaseClass is in your own codebase, then you can do:
abstract public class BaseClass
{
abstract public double MyPop { get; protected set; }
}
public class DClass : BaseClass
{
private double _myProp;
public override double MyProp
{
get { return _myProp; }
protected set { _myProp = value; }
}
}
EDIT: You can then go make a public method in DClass SetMyProp(double myProp) or the like. The class design for your domain model should be clear about or speak for itself why you can't set the property directly in the base class and why you can do so in the derived one.
Are you sure that doing what you are trying to do would be a good design if you found a way to do it?
It would allow objects of the subclass to make state changes that objects of the parent class can not make. Wouldn't that violate the Liskov Substitution Principle?
You could do something like this:
abstract class TestBase
{
public abstract int Int { get; }
}
class TestDerivedHelper : TestBase
{
private int _Int;
public override int Int
{
get
{
return _Int;
}
}
protected void SetInt(int value)
{
this._Int = value;
}
}
class TestDerived : TestDerivedHelper
{
public new int Int
{
get { return base.Int; }
set { base.SetInt(value); }
}
}
Using TestDerived will have the functionality you're looking for. The only drawback I can see from this method is that you have to implement every abstract method in TestDerivedHelper, but it gives you more control later.
Hope this helps. ;)
The reason that this is not possible is due to the way parameters are "Magicked" into existence by C#. When you define a parameter, C# creates a private field that the implicit getter and setter manipulate. If there is no setter in the base class, it's impossible to change this variable from a method written in a sub class (as the private flag prohibits even sub classes from accessing it). What usually happens is it uses the implicit setter of the base class instead.
I wouldn't advise putting the set in the base class if not all sub classes can do it, because this goes against the whole principle of polymorphic programming (any abstract method defined in the abstract class must be implemented by a subclass). Creating a special setter method, as described in other answers is probably the best way go.
Siege
abstract class TestBase
{
public abstract int Int { get; }
}
class TestDerivedHelper : TestBase
{
private int _Int;
public override int Int
{
get
{
return _Int;
}
}
protected void SetInt(int value)
{
this._Int = value;
}
}
class TestDerived : TestDerivedHelper
{
public new int Int
{
get { return base.Int; }
set { base.SetInt(value); }
}
}
Using TestDerived will have the functionality you're looking for. The
only drawback I can see from this method is that you have to implement
every abstract method in TestDerivedHelper, but it gives you more
control later.
I use this approach and works very well for me.
Also, I made my "TestDerivedHelper" class abstract too, then all the methods must be implemented on "TestDerived" class.
Even though this thread is old I'm positing my solution, in case it helps someone. It is not my own but is based off answers in other SO topics.
public abstract BaseClass
{
public double MyPoP { get { return GetMyPoP; } }
protected abstract double GetMyPoP { get; }
}
public class DClass: BaseClass
{
public new double MyPoP { get; set; }
protected override double GetMyPop { get { return MyPoP; } }
}
This solution adds an extra line of code for each such property that needs accessor modified. However, there is no change to external visibility and provides needed functionality.
public abstract class BaseClass
{
public abstract double MyPop { get; }
}
public class DClass: BaseClass
{
private double _myPop = 0;
public override double MyPop
{
get { return _myPop; }
}
// some other methods here that use the _myPop field
}
If you need to set the property from outside DClass then maybe it would be better to put the setter into the base class.
EDIT:
OK I may have been hasty with this response, but I've given it some more thought now.
Do you have to use an abstract base class? If it's not required, try this:
public interface ISomeRelevantName
{
double MyPop { get; }
}
public class DClass : ISomeRelevantName
{
public double MyPop { get; set; }
}
Why not just have a property in the base class that has a private setter, then in your subclass that needs the setter, override it and make it public.
You cannot override the set accessor since the base class has no set accessor defined.
What you can do is use the new keyword to hide the base classes implementation, but that may not be what you want.