I tried to solve inheritance problem in my application. It's basically something like this:
interface IAbcBase
{
int? Value { get; }
}
interface IAbc : IAbcBase
{
new int Value { get; }
}
class BaseA : IAbcBase
{
public virtual int? Value => (this as A)?.Value;
}
class A : BaseA, IAbc
{
// public override int? Value => 4; // line A
public new int Value => 4; // line B
}
I want to hide property Value from BaseA and replace it by non nullable property on A. But at the same time I also want to be able to override property Value to provide more effective definition for Value in case I assign it to variable of type BaseA.
BaseA a = new A();
var b = a.Value; // b is int? which is fine. But ineffective definition was used instead of line A
Is it possible to somehow override property and also hide it at same time (ie uncomment both lines A and B)? In my real application the definition on base class is not that simple and I would love to provide much more effective definition and also hide that Value.
Solution could be to not hide member from base and instead use another name. For example ValueNotNull and mark overriden method as obsolete. It's not that simple though because I can't modify members from interfaces IAbcBase and IAbc. I don't like this solution because then the implementation of IAbc must be explicit so I can override member from BaseA and then I am not able to use name Value on A which is what I want because it's basically non nullable equivalent of Value on BaseA.
I hope I described my issue well. In case any details are needed, I will edit
/// Edit:
I was asked to provide examples of use cases if both definitions on line A and line B were allowed. In my real application, I have following definitions (simplified):
internal sealed class StandardDefinition : Definition
{
public Definition Previous { get; }
public new int NodesCount { get; }
}
internal sealed class RootDefinition : Definition
{
}
internal abstract class Definition
{
public int? NodesCount => (this as StandardDefinition)?.NodesCount;
}
Root node is basically start position for chess analysis which is not necessarily standard start position. NodesCount is number of nodes which were used for analysing this move. It's something I don't have for root position because I never get start position as a result from any analysis so there is nothing to return (there is much more properties like that, I simplified a lot).
I use mainly variables of Definition except one place in code right after analysis is done and I get StandardDefinition. Thus mostly ineffective definitions for NodesCount and other similar properties are used instead of using definition from StandardDefinition. That's why I want to be able to override, because most instances are obviously of type StandardDefinition. There is only few RootDefinitions. Most of that casting and testing for null is absolutely unnecessary. After I analyse position, I get StandardDefinition and now I would like to be able to hide old definition which is nullable and provide definition which just returns nonnulable nodes count used for analysing this position. Again to avoid all unnecessary casting, etc.
No, basically, if you mean the public API on A. The only solution to this is to introduce an extra layer:
abstract class AlmostA : BaseA
{
public override int? Value => GetValue();
protected int GetValue() => 4;
}
class A : AlmostA, IAbc
{
public new int Value => GetValue();
}
If you only mean for the purposes of satisfying the IAbc interface, then "explicit interface implementation" is your friend:
class A : BaseA, IAbc
{
private int GetValue() => 4;
public override int? Value => GetValue();
int IAbc.Value => GetValue();
}
Is there a specific reason why the following is not possible?
class ClassOfInts : IHaveInts
{
public MyInt IntHolder { get; }
// This solves my use case but i'm unsure why this is necessary
// IInt IHaveInts.IntHolder { get => IntHolder; }
}
interface IHaveInts
{
IInt IntHolder { get; }
}
class MyInt : IInt
{
public int TheInt { get; }
}
interface IInt
{
int TheInt { get; }
}
I would think that the above code successfully implements IHaveInts since MyInt implements IInt.
Is there a specific reason why the following is not possible?
Well, the short answer is: "because the C# specification doesn't allow it". Longer answers typically involve some amount of speculation as to what was in the thought process of the C# language designers. That makes such questions primarily opinion based.
However, they did make a deliberate choice that interface members have to be implemented precisely as declared, and that choice is why you can't do that. A likely reason behind that choice is that they would have to special-case read-only properties, because allowing the property to be implemented that way for a writeable property would be unsafe. Were they to allow that, you'd be able to assign any IInt value to the property which expects only MyInt values.
That said, depending on what you're actually trying to do, you might be able to use generic type variance to support your scenario. This will compile fine:
public class ClassOfInts : IHaveInts<MyInt>
{
public MyInt IntHolder { get; }
}
public interface IHaveInts<out T> where T : IInt
{
T IntHolder { get; }
}
Declared that way, the following works fine:
static void M()
{
IHaveInts<IInt> haveInts = new ClassOfInts();
}
This is semantically equivalent to what you were originally trying to do. That is, when using the interface type, you have a property of type IInt, but you want to implement that property with a member that returns a value of type MyInt.
Why is it that when I set a shadowed field (declared using new keyword) in a base class constructor, the field that was shadowed gets set but not the field that is shadowing?
I thought that this.GetType() referred to the outermost class all the way down into base class calls including the constructor. I also thought that shadowing made the shadowed field not accessible.
In my quick watch I can see two fields, the shadowed one that got set and the shadowing one (of the subclass) that is still not initialized.
I fixed it by explicitly setting the shadowing field in the subclass constructor after it calls the base class constructor, but I'd still like to know why it acts this way. .Net Fiddle
using System;
public class Program
{
public static void Main()
{
SubClass subClass = new SubClass(2);
Console.WriteLine(subClass.MyField);
}
}
public class BaseClass
{
public BaseClass(int value)
{
MyField = value; // This doesn't point to SubClass.MyField
}
public int MyField;
}
public class SubClass : BaseClass
{
public SubClass(int value):base(value)
{
}
public new int MyField = 4;
}
Update
After reviewing the answers, I see I didn't ask what I wanted to know in the most direct way. Sorry for any inconvenience. Here's what I really want to know:
I do understand shadowing. I don't agree with it. I don't think it should be allowed for fields (as long as overridable fields were made a language feature). I don't see the point in shadowing fields and having the shadowed field hanging around. I do however see the point in overridable fields and I don't understand why that language feature doesn't exist when it exists for properties and methods. So, why have shadowing on fields? Why is there not overriding on fields?
We have
I also thought that shadowing made the shadowed field not accessible.
Followed by
I do understand shadowing.
I'm not entirely sure that you do. You've already expressed one false belief about shadowing; how do we know there aren't more?
I don't agree with it.
Your opinion is noted. I note that you are not required to use the feature if you don't like it.
I don't think it should be allowed for fields (as long as overridable fields were made a language feature).
Noted.
I do however see the point in overridable fields and I don't understand why that language feature doesn't exist when it exists for properties and methods.
Fields should be private implementation details of classes. If they are, then there is no accessible name to shadow or override, so the problem is moot. A feature that we would want no one to use is a bad feature.
So, why have shadowing on fields?
Suppose there is a protected field in a derived class. Now consider the brittle base class problem. Work through a number of such scenarios; you're critiquing a language design choice, so think like the language designers think. What do you conclude from your investigation into typical brittle base class scenarios?
Why is there not overriding on fields?
Because (1) we have no mechanism for overriding fields; methods have vtables but there is no vtable mechanism for fields. And (2) fields should be private implementation details of classes, and therefore there is never a need to override them. If you want to override a field, make a property that wraps it and override that. The code change is tiny to go from a field to a virtual property.
Fields should be in the mechanism domain of the class; properties are in the business domain. Specialization of behaviour belongs in the business domain.
public class BaseClass
{
public BaseClass(int value)
{
MyField = value; // This doesn't point to SubClass.MyField
}
public int MyField;
}
The base class doesn't know about its derived types. MyField = value does exactly what it says it's doing: it assigns MyField with value.
public class SubClass : BaseClass
{
public SubClass(int value):base(value)
{
}
public new int MyField = 4;
}
Are you expecting the value 4 to propagate to the base type? Your question is quite hard to answer, because it's not exactly clear what your definition of "intuitive" and expectations are.... and your example code is very poor OOP design.
There aren't lots of valid reasons to ever expose a public field, base class or not.
Let me rephrase your example:
public abstract class BaseClass
{
protected BaseClass(int value)
{
_value = value;
}
private int _value;
public virtual int Value { get { return _value; } set { _value = value; } }
}
public class SubClass : BaseClass
{
public SubClass(int value) : base(value)
{
}
public new int Value { get; set; } // hides base class member
}
Now. SubClass.Value is its own thing - if you want to access the value that was passed down the constructor, you need to do so via the base class.
The base class member doesn't "cease to exist", it's only hidden, or shadowed, by a new member in a derived type, that just so happens to have the same identifier:
var foo = new SubClass(42);
Console.WriteLine(foo.Value);
Console.WriteLine(((BaseClass)foo).Value);
Console.ReadKey();
This code outputs 0, then 42 - because when foo.Value gets accessed the SubClass says "hey base class, let me handle this - I have my own definition of Value, and this call mine to pick up." ...and returns 0 because, well, it's never actually assigned; the 42 is only visible via the base class.
That is what member shadowing does.
And it works the same even without the new keyword - the new keyword merely suppresses a compiler warning that says "you're hiding a base class member here, are you really totally completely sure you intend to be doing this?" - because in a normal world, that typically isn't what you would want to be doing.
Now, notice I made the Value property virtual. What happens if you override it instead?
public class SubClass : BaseClass
{
public SubClass(int value)
: base(value)
{
}
public override int Value { get; set; }
}
The little console program above (a few snippets up) will now output 0 and 0 - because the subclass' Value overrides the base class member, effectively telling C# to resolve member calls to the derived type. So to output the 42 you're passing in, because you're overriding the member, you become responsible for how it works - the _value private field in the base class still says 42, but the Value property being overridden, the field is left unused.
So you assign it in your derived type's constructor (here sealing the class to avoid a virtual member call in the constructor):
public sealed class SubClass : BaseClass
{
public SubClass(int value)
: base(0)
{
Value = value;
}
public override int Value { get; set; }
}
So, here the derived type is passing 0 to the base class, and overriding the member. What does the little snippet output for 42 now?
static void Main(string[] args)
{
var foo = new SubClass(42);
Console.WriteLine(foo.Value);
Console.WriteLine(((BaseClass)foo).Value);
Console.ReadKey();
}
it will output 42 for both the derived and the downcasted calls, because the type cast is now redundant, since the virtual member is overridden.
Not sure why you want to do this, but here is how :
public class BaseClass
{
public BaseClass(int value)
{
SetValue(x => x.MyField, value);
}
public int MyField;
public void SetValue<TField>(Expression<Func<BaseClass, TField>> memberSelector, TField value)
{
var expression = memberSelector.Body as MemberExpression;
if (expression == null)
throw new MemberAccessException();
this.GetType().GetField(expression.Member.Name)
.SetValue(this, value);
}
}
Keep in mind that shadowing a field just makes a new field, it is in no way related to the field in the base class (except by virtue of the fact that you've given it the same name).
Simply put, you haven't written any code that sets the field in SubClass, you've only written code that sets the field in BaseClass:
public class BaseClass
{
public BaseClass(int value)
{
MyField = value; // This doesn't point to SubClass.MyField
}
public int MyField;
}
MyField here can only ever refer to the MyField in BaseClass. It can't possibly know that you're going to create a subclass later and put a field in it with the same name. And even if you do that, all you've done is create a different field with the same name, so why would setting BaseClass.MyField also set the mostly unrelated SubClass.MyField?
I have an interface 'IBase' that specifies a nullable int. A later interface 'IDerived' hides the nullable int and 'redefines' it as non-nullable.
interface IBase
{
int? Redefineable { get; set; }
}
interface IDerived : IBase
{
new int Redefineable { get; set; }
}
The class that implements these interfaces must explicitly implement the hidden property, however it's private so the client can't see it.
class TheClass : IDerived
{
public int Redefineable { get; set; }
int? IBase.Redefineable { get; set; }
}
However, even though it's a private property, I can still access it through the IBase interface!
var o = new TheClass();
o.Redefineable = 1; // ok
var hack = o as IBase;
hack.Redefineable = null; // uh!
This seems like some kind of violation of C# access modifiers, but either way it isn't really what I had in mind for redefining (not just hiding) a property. It's correct in the sense that it does what you're asking, get an IBase interface which has a nullable int but this is non-intuitive to the client who could then modify the wrong version of the property.
What I really want, is that if the client accesses IBase.Redefinable, then it behaves as if it's accessing the IDerived.Redefinable property, the 'real' property of TheClass. That way it's actually redefined, as in back through the hierarchy.
class TheClass : IDerived
{
public int Redefineable { get; set; }
int? IBase.Redefineable {
get {
// redirect to redefined property
return this.Redefineable;
}
set
{
// stop client setting it to null
if (!value.HasValue)
throw new InvalidOperationException();
// redirect to redefined property
this.Redefineable = value.Value;
}
}
}
This just feels like a hack, almost as if I'm missing something, so I want to ask if anyone knows a better/alternative way to implement re-definable properties?
However, even though it's a private property, I can still access it through the IBase interface!
It's not a private property. It's just a property using explicit interface implementation. That means it's public through the interface, but only available through the interface. Explicit interface implementation is mostly designed to make it feasible to implement "contradictory" interfaces, as well as being used to "discourage" (but not prohibit) the use of some interface methods. It's not meant to give the impression that the members don't exist at all.
Fundamentally, it sounds like you shouldn't be using inheritance here - if you don't want something to be able to act as an IBase, you shouldn't inherit from IBase.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Why is the following C# code not allowed:
public abstract class BaseClass
{
public abstract int Bar { get;}
}
public class ConcreteClass : BaseClass
{
public override int Bar
{
get { return 0; }
set {}
}
}
CS0546 'ConcreteClass.Bar.set': cannot override because 'BaseClass.Bar' does not have an overridable set accessor
I think the main reason is simply that the syntax is too explicit for this to work any other way. This code:
public override int MyProperty { get { ... } set { ... } }
is quite explicit that both the get and the set are overrides. There is no set in the base class, so the compiler complains. Just like you can't override a method that's not defined in the base class, you can't override a setter either.
You might say that the compiler should guess your intention and only apply the override to the method that can be overridden (i.e. the getter in this case), but this goes against one of the C# design principles - that the compiler must not guess your intentions, because it may guess wrong without you knowing.
I think the following syntax might do nicely, but as Eric Lippert keeps saying, implementing even a minor feature like this is still a major amount of effort...
public int MyProperty
{
override get { ... } // not valid C#
set { ... }
}
or, for autoimplemented properties,
public int MyProperty { override get; set; } // not valid C#
It's possible.
tl;dr– You can override a get-only method with a setter if you want. It's basically just:
Create a new property that has both a get and a set using the same name.
override the prior get to alias the new get.
This enables us to override properties with get/set even if they lacked a setter in their base definition.
Situation: Pre-existing get-only property.
You have some class structure that you can't modify. Maybe it's just one class, or it's a pre-existing inheritance tree. Whatever the case, you want to add a set method to a property, but can't.
public abstract class A // Pre-existing class; can't modify
{
public abstract int X { get; } // You want a setter, but can't add it.
}
public class B : A // Pre-existing class; can't modify
{
public override int X { get { return 0; } }
}
Problem: Can't override the get-only with get/set.
You want to override with a get/set property, but it won't compile.
public class C : B
{
private int _x;
public override int X
{
get { return _x; }
set { _x = value; } // Won't compile
}
}
Solution: Use an abstract intermediate layer.
While you can't directly override with a get/set property, you can:
Create a new get/set property with the same name.
override the old get method with an accessor to the new get method to ensure consistency.
So, first you write the abstract intermediate layer:
public abstract class C : B
{
// Seal off the old getter. From now on, its only job
// is to alias the new getter in the base classes.
public sealed override int X { get { return this.XGetter; } }
protected abstract int XGetter { get; }
}
Then, you write the class that wouldn't compile earlier. It'll compile this time because you're not actually override'ing the get-only property; instead, you're replacing it using the new keyword.
public class D : C
{
private int _x;
public new virtual int X
{
get { return this._x; }
set { this._x = value; }
}
// Ensure base classes (A,B,C) use the new get method.
protected sealed override int XGetter { get { return this.X; } }
}
Result: Everything works!
var d = new D();
var a = d as A;
var b = d as B;
var c = d as C;
Print(a.X); // Prints "0", the default value of an int.
Print(b.X); // Prints "0", the default value of an int.
Print(c.X); // Prints "0", the default value of an int.
Print(d.X); // Prints "0", the default value of an int.
// a.X = 7; // Won't compile: A.X doesn't have a setter.
// b.X = 7; // Won't compile: B.X doesn't have a setter.
// c.X = 7; // Won't compile: C.X doesn't have a setter.
d.X = 7; // Compiles, because D.X does have a setter.
Print(a.X); // Prints "7", because 7 was set through D.X.
Print(b.X); // Prints "7", because 7 was set through D.X.
Print(c.X); // Prints "7", because 7 was set through D.X.
Print(d.X); // Prints "7", because 7 was set through D.X.
Discussion.
This method allows you to add set methods to get-only properties. You can also use it to do stuff like:
Change any property into a get-only, set-only, or get-and-set property, regardless of what it was in a base class.
Change the return type of a method in derived classes.
The main drawbacks are that there's more coding to do and an extra abstract class in the inheritance tree. This can be a bit annoying with constructors that take parameters because those have to be copy/pasted in the intermediate layer.
Bonus: You can change the property's return-type.
As a bonus, you can also change the return type if you want.
If the base definition was get-only, then you can use a more-derived return type.
If the base definition was set-only, then you can use a less-derived return type.
If the base definition was already get/set, then:
you can use a more-derived return type if you make it set-only;
you can use a less-derived return type if you make it get-only.
In all cases, you can keep the same return type if you want.
I stumbled across the very same problem today and I think I have a very valid reason for wanting this.
First I'd like to argue that having a get-only property doesn't necessarily translate into read-only. I interpret it as "From this interface/abstract class you can get this value", that doesn't mean that some implementation of that interface/abstract class won't need the user/program to set this value explicitly. Abstract classes serve the purpose of implementing part of the needed functionality. I see absolutely no reason why an inherited class couldn't add a setter without violating any contracts.
The following is a simplified example of what I needed today. I ended up having to add a setter in my interface just to get around this. The reason for adding the setter and not adding, say, a SetProp method is that one particular implementation of the interface used DataContract/DataMember for serialization of Prop, which would have been made needlessly complicated if I had to add another property just for the purpose of serialization.
interface ITest
{
// Other stuff
string Prop { get; }
}
// Implements other stuff
abstract class ATest : ITest
{
abstract public string Prop { get; }
}
// This implementation of ITest needs the user to set the value of Prop
class BTest : ATest
{
string foo = "BTest";
public override string Prop
{
get { return foo; }
set { foo = value; } // Not allowed. 'BTest.Prop.set': cannot override because 'ATest.Prop' does not have an overridable set accessor
}
}
// This implementation of ITest generates the value for Prop itself
class CTest : ATest
{
string foo = "CTest";
public override string Prop
{
get { return foo; }
// set; // Not needed
}
}
I know this is just a "my 2 cents" post, but I feel with the original poster and trying to rationalize that this is a good thing seems odd to me, especially considering that the same limitations doesn't apply when inheriting directly from an interface.
Also the mention about using new instead of override does not apply here, it simply doesn't work and even if it did it wouldn't give you the result wanted, namely a virtual getter as described by the interface.
I agree that not being able to override a getter in a derived type is an anti-pattern. Read-Only specifies lack of implementation, not a contract of a pure functional (implied by the top vote answer).
I suspect Microsoft had this limitation either because the same misconception was promoted, or perhaps because of simplifying grammar; though, now that scope can be applied to get or set individually, perhaps we can hope override can be too.
The misconception indicated by the top vote answer, that a read-only property should somehow be more "pure" than a read/write property is ridiculous. Simply look at many common read only properties in the framework; the value is not a constant / purely functional; for example, DateTime.Now is read-only, but anything but a pure functional value. An attempt to 'cache' a value of a read only property assuming it will return the same value next time is risky.
In any case, I've used one of the following strategies to overcome this limitation; both are less than perfect, but will allow you to limp beyond this language deficiency:
class BaseType
{
public virtual T LastRequest { get {...} }
}
class DerivedTypeStrategy1
{
/// get or set the value returned by the LastRequest property.
public bool T LastRequestValue { get; set; }
public override T LastRequest { get { return LastRequestValue; } }
}
class DerivedTypeStrategy2
{
/// set the value returned by the LastRequest property.
public bool SetLastRequest( T value ) { this._x = value; }
public override T LastRequest { get { return _x; } }
private bool _x;
}
You could perhaps go around the problem by creating a new property:
public new int Bar
{
get { return 0; }
set {}
}
int IBase.Bar {
get { return Bar; }
}
I can understand all your points, but effectively, C# 3.0's automatic properties get useless in that case.
You can't do anything like that:
public class ConcreteClass : BaseClass
{
public override int Bar
{
get;
private set;
}
}
IMO, C# should not restrict such scenarios. It's the responsibility of the developer to use it accordingly.
The problem is that for whatever reason Microsoft decided that there should be three distinct types of properties: read-only, write-only, and read-write, only one of which may exist with a given signature in a given context; properties may only be overridden by identically-declared properties. To do what you want it would be necessary to create two properties with the same name and signature--one of which was read-only, and one of which was read-write.
Personally, I wish that the whole concept of "properties" could be abolished, except that property-ish syntax could be used as syntactic sugar to call "get" and "set" methods. This would not only facilitate the 'add set' option, but would also allow for 'get' to return a different type from 'set'. While such an ability wouldn't be used terribly often, it could sometimes be useful to have a 'get' method return a wrapper object while the 'set' could accept either a wrapper or actual data.
Here is a work-around in order to achieve this using Reflection:
var UpdatedGiftItem = // object value to update;
foreach (var proInfo in UpdatedGiftItem.GetType().GetProperties())
{
var updatedValue = proInfo.GetValue(UpdatedGiftItem, null);
var targetpropInfo = this.GiftItem.GetType().GetProperty(proInfo.Name);
targetpropInfo.SetValue(this.GiftItem, updatedValue,null);
}
This way we can set object value on a property that is readonly. Might not work in all the scenarios though!
You should alter your question title to either detail that your question is solely in regards to overriding an abstract property, or that your question is in regards to generally overriding a class's get-only property.
If the former (overriding an abstract property)
That code is useless. A base class alone shouldn't tell you that you're forced to override a Get-Only property (Perhaps an Interface). A base class provides common functionality which may require specific input from an implementing class. Therefore, the common functionality may make calls to abstract properties or methods. In the given case, the common functionality methods should be asking for you to override an abstract method such as:
public int GetBar(){}
But if you have no control over that, and the functionality of the base class reads from its own public property (weird), then just do this:
public abstract class BaseClass
{
public abstract int Bar { get; }
}
public class ConcreteClass : BaseClass
{
private int _bar;
public override int Bar
{
get { return _bar; }
}
public void SetBar(int value)
{
_bar = value;
}
}
I want to point out the (weird) comment: I would say a best-practice is for a class to not use its own public properties, but to use its private/protected fields when they exist. So this is a better pattern:
public abstract class BaseClass {
protected int _bar;
public int Bar { get { return _bar; } }
protected void DoBaseStuff()
{
SetBar();
//Do something with _bar;
}
protected abstract void SetBar();
}
public class ConcreteClass : BaseClass {
protected override void SetBar() { _bar = 5; }
}
If the latter (overriding a class's get-only property)
Every non-abstract property has a setter. Otherwise it's useless and you shouldn't care to use it. Microsoft doesn't have to allow you to do what you want. Reason being: the setter exists in some form or another, and you can accomplish what you want Veerryy easily.
The base class, or any class where you can read a property with {get;}, has SOME sort of exposed setter for that property. The metadata will look like this:
public abstract class BaseClass
{
public int Bar { get; }
}
But the implementation will have two ends of the spectrum of complexity:
Least Complex:
public abstract class BaseClass
{
private int _bar;
public int Bar {
get{
return _bar;
}}
public void SetBar(int value) { _bar = value; }
}
Most Complex:
public abstract class BaseClass
{
private int _foo;
private int _baz;
private int _wtf;
private int _kthx;
private int _lawl;
public int Bar
{
get { return _foo * _baz + _kthx; }
}
public bool TryDoSomethingBaz(MyEnum whatever, int input)
{
switch (whatever)
{
case MyEnum.lol:
_baz = _lawl + input;
return true;
case MyEnum.wtf:
_baz = _wtf * input;
break;
}
return false;
}
public void TryBlowThingsUp(DateTime when)
{
//Some Crazy Madeup Code
_kthx = DaysSinceEaster(when);
}
public int DaysSinceEaster(DateTime when)
{
return 2; //<-- calculations
}
}
public enum MyEnum
{
lol,
wtf,
}
My point being, either way, you have the setter exposed. In your case, you may want to override int Bar because you don't want the base class to handle it, don't have access to review how it's handling it, or were tasked to hax some code real quick'n'dirty against your will.
In both Latter and Former (Conclusion)
Long-Story Short: It isn't necessary for Microsoft to change anything. You can choose how your implementing class is set up and, sans the constructor, use all or none of the base class.
Solution for only a small subset of use cases, but nevertheless: in C# 6.0 "readonly" setter is automatically added for overridden getter-only properties.
public abstract class BaseClass
{
public abstract int Bar { get; }
}
public class ConcreteClass : BaseClass
{
public override int Bar { get; }
public ConcreteClass(int bar)
{
Bar = bar;
}
}
This is not impossible. You simply have to use the "new" keyword in your property. For example,
namespace {
public class Base {
private int _baseProperty = 0;
public virtual int BaseProperty {
get {
return _baseProperty;
}
}
}
public class Test : Base {
private int _testBaseProperty = 5;
public new int BaseProperty {
get {
return _testBaseProperty;
}
set {
_testBaseProperty = value;
}
}
}
}
It appears as if this approach satisfies both sides of this discussion. Using "new" breaks the contract between the base class implementation and the subclass implementation. This is necessary when a Class can have multiple contracts (either via interface or base class).
Hope this helps
Because that would break the concept of encapsulation and implementation hiding. Consider the case when you create a class, ship it, and then the consumer of your class makes himself able to set a property for which you originally provide a getter only. It would effectively disrupt any invariants of your class which you can depend on in your implementation.
Because a class that has a read-only property (no setter) probably has a good reason for it. There might not be any underlying datastore, for example. Allowing you to create a setter breaks the contract set forth by the class. It's just bad OOP.
A read-only property in the base class indicates that this property represents a value that can always be determined from within the class (for example an enum value matching the (db-)context of an object). So the responsibillity of determining the value stays within the class.
Adding a setter would cause an awkward issue here:
A validation error should occur if you set the value to anything else than the single possible value it already has.
Rules often have exceptions, though. It is very well possible that for example in one derived class the context narrows the possible enum values down to 3 out of 10, yet the user of this object still needs to decide which one is correct. The derived class needs to delegate the responsibillity of determining the value to the user of this object.
Important to realize is that the user of this object should be well aware of this exception and assume the responsibillity to set the correct value.
My solution in these kind of situations would be to leave the property read-only and add a new read-write property to the derived class to support the exception.
The override of the original property will simply return the value of the new property.
The new property can have a proper name indicating the context of this exception properly.
This also supports the valid remark: "make it as hard as possible for misunderstandings to crop up" by Gishu.
Because at the IL level, a read/write property translates into two (getter and setter) methods.
When overriding, you have to keep supporting the underlying interface. If you could add a setter, you would effectively be adding a new method, which would remain invisible to the outside world, as far as your classes' interface was concerned.
True, adding a new method would not be breaking compatibility per se, but since it would remain hidden, decision to disallow this makes perfect sense.
Because the writer of Baseclass has explicitly declared that Bar has to be a read-only property. It doesn't make sense for derivations to break this contract and make it read-write.
I'm with Microsoft on this one.
Let's say I'm a new programmer who has been told to code against the Baseclass derivation. i write something that assumes that Bar cannot be written to (since the Baseclass explicitly states that it is a get only property).
Now with your derivation, my code may break. e.g.
public class BarProvider
{ BaseClass _source;
Bar _currentBar;
public void setSource(BaseClass b)
{
_source = b;
_currentBar = b.Bar;
}
public Bar getBar()
{ return _currentBar; }
}
Since Bar cannot be set as per the BaseClass interface, BarProvider assumes that caching is a safe thing to do - Since Bar cannot be modified. But if set was possible in a derivation, this class could be serving stale values if someone modified the _source object's Bar property externally. The point being 'Be Open, avoid doing sneaky things and surprising people'
Update: Ilya Ryzhenkov asks 'Why don't interfaces play by the same rules then?'
Hmm.. this gets muddier as I think about it.
An interface is a contract that says 'expect an implementation to have a read property named Bar.' Personally I'm much less likely to make that assumption of read-only if I saw an Interface. When i see a get-only property on an interface, I read it as 'Any implementation would expose this attribute Bar'... on a base-class it clicks as 'Bar is a read-only property'. Of course technically you're not breaking the contract.. you're doing more. So you're right in a sense.. I'd close by saying 'make it as hard as possible for misunderstandings to crop up'.