How to redefine a property in C# through interface inheritance? - c#

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.

Related

Accessibility on interfaces

With the recent changes to interfaces that came in C# 8.0, I'm a little confused about how the accessibilities are supposed to work (which are now valid on interfaces, they didn't used to be).
This seemingly simple example does not work as you'd expect:
public interface IFoo
{
public string Bar { get; internal set; }
}
public class Foo : IFoo
{
public string Bar { get; internal set; } //Error - Non-public accessor "Bar.set" cannot implement accessor from interface IFoo
}
The only "working" code I can seem to get for the IFoo interface is this:
public interface IFoo
{
public string Bar { get; internal set; }
}
public class Foo : IFoo
{
string IFoo.Bar { get; set; }
}
In other words, the interface must be implemented explicitly.
Why is the first example invalid? Why does this situation require explicit implementation?
My explanation, with some conjecture on my side:
There's an old rule that if you'd rather not implement an interface member as a public class member, then you must use explicit implementation. This allows to make prescribed interface members "hard to access" because in your implementation they are not suitable for public usage. Note that even then the implementation remains public.
This also seems to apply to interface parts that can now declare themselves with less-than-public visibility, it now seems to be: any member of an interface that *isn't fully public* or that you *don't want to implement as public* must use explicit implementation. Note: I have no source for this, I distilled it from what I see is happening.
Since your property is only "half public", apparently all of it falls under that rule.
Then there is another rule, quoting from the documentation:
An explicit interface implementation doesn't have an access modifier since it isn't accessible as a member of the type it's defined in. Instead, it's only accessible when called through an instance of the interface.
This explains why as soon as you use explicit implementation (forced or not), you can't add access modifiers of your own because the interface defines the applicable access modifiers (with public being the default if omitted).
Consequences of doing this
To access even the public getter, all client code needs to use IFoo:
var f = new Foo(); var x = ((IFoo)f).Bar; // works
IFoo f = new Foo(); var x = f.Bar; // works
var x = new Foo().Bar; // does not compile
It's up to you to decide if it is worth to force this requirement onto your callers.
If needed then I see two ways to avoid that requirement, first way means leaving the internal setter out of the interface and only put it in Foo, but then code using the setter must use Foo as the variable type, it can't use IFoo, while code using the getter can do whatever it likes:
public interface IFoo
{
public string Bar { get; } // no setter (and you can omit `public`)
}
public class Foo : IFoo
{
public string Bar { get; internal set; } // add internal setter as class member
}
Second way, having an internal void SetBar(string value) in the interface, now all code using SetBar() must use IFoo as the variable type, and code using the getter can do whatever it likes:
public interface IFoo
{
public string Bar { get; }
internal void SetBar(string value);
}
public class Foo : IFoo
{
public string Bar { get; private set; } // add private setter as class member
void IFoo.SetBar(string value) { Bar = value; } // use private setter
}

Implement interface using concrete implementations of abstract interface members

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.

How to hide set method of an implemented property from an interface in C#?

Greetings everyone...
If I have the following interface:
interface IMyInterface
{
int property { get; set; }
}
And the following implementation:
class MyClass : IMyInterface
{
// anything
}
How can I hide the set method of property from the instances of MyClass... In other words, I don't want the set method of property to be public, is that possible?
It would be easy to do with abstract class:
abstract class IMyInterface
{
int property { get; protected set; }
}
Then I could only set the property within the class that implements the abstract class above...
Don't have the set in the interface to begin with. You can still implement it as private.
You can't "hide" it, it's part of the contract. If you don't want it to be part of the contract, don't define it.
If you use the following interface the set method will be unavailable when classes are manipulated via the interface:
interface IMyInterface
{
int property { get; }
}
You could then implement the class like this:
class MyClass : IMyInterface
{
int property { get; protected set; }
}
If some implementations will only implement some parts of an interface, it may be a good idea to subdivide the interface into the parts which each implementation will either implement completely or not at all, and then define interfaces which inherit all the common combinations of them. Adapting your example:
interface IMyReadableInterface
{
int property { get; }
}
interface IMyFullInterface : IMyReadableInterface
{
new int property { get; set; }
}
Classes which want to support read-write access should implement IMyFullInterface; those which want to only support read access should only implement IMyReadableInterface. This segregation will not require any extra work for implementations of either interface which are written in C# and implement property implicitly. Code which implements property in VB, or explicitly implements property in C#, will have to define two implementations of property--a read-only one and a read-write one, but such is life. Note that while one could define an IMyWritableInterface which just had a setter, and have IMyFullInterface inherit both IMyReadableInterface and IMyWritableInterface, IMyFullInterface would still have to define a read-write property of its own, and when using explicit implementation one would then have to define three properties (I really don't understand why C# can't use a read-only and write-only property together as thought they were a read-write property, but it can't).
Assuming you need the setter to be part of the interface but for some reason it does not make sense for it to be used on a particular implementer (in this case MyClass) you can always throw an exception in the setter (such as an InvalidOperationException). This will not protect you at compile time, only at run time. It is a bit strange though, as code that operates on the interface has no idea whether calling the setter is allowed.
There are certainly cases where you want the interface to have a set and then hide it in some concrete class.
I believe the code below shows what we want to accomplish. I.e. the implementation hides the setter, but any IMyInterface aware component will have access to it.
public static void Main()
{
var myClass = new MyClass();
myClass.Property = 123; // Error
((IMyInterface)myClass).Property = 123; // OK
}
It's basically the same pattern you often see for IDisposable.Dispose() where you have an Explicit Interface Implementation. Here's an example for completeness.
public interface IMyInterface
{
int Property { get; set; }
}
public class MyClass : IMyInterface, IDisposable
{
public int Property { get; private set; }
int IMyInterface.Property
{
get => Property;
set => Property = value;
}
void IDisposable.Dispose() {}
}
Too much typing :(
C# doesn't help us much here. Ideally, it would be possible to have an explicit interface implementation for the setter:
// In C# 10 maybe we can do this instead:
public class MyFutureClass : IMyInterface
{
public int Property { get; IMyInterface.set; }
}
See C# feature proposal here.
There is no protected or private in interface, everything is public. Either you don't define any set or use it as public.

interface inheritance without hiding

If I write class, then all ok
class C
{
protected int _attr;
int attr { get { return _attr; } }
}
class CWithSet : C
{
int attr { set { _attr = value; } }
}
But, if I write interface
interface I
{
int attr { get; }
}
interface IWithSet : I
{
int attr { set; }
}
then I have warring: "'IWithSet.attr' hides inherited member 'I.attr'. Use the new keyword if hiding was intended."
How to write, so as not to get warning?
From the C# Specification: The inherited members of an interface are specifically not part of the declaration space of the interface. Thus, an interface is allowed to declare a member with the same name or signature as an inherited member. When this occurs, the derived interface member is said to hide the base interface member. Hiding an inherited member is not considered an error, but it does cause the compiler to issue a warning. To suppress the warning, the declaration of the derived interface member must include a new modifier to indicate that the derived member is intended to hide the base member. (Interface members) The correct implementation is:
interface IWithSet : I
{
new int attr { get; set; }
}
You might want to consider whether it's worth redefining the semantics of your interfaces. What I mean is, it might make sense to just have a separate write-only interface in addition to the read-only one you've defined as "I".
Here's an example:
interface IReadOnly
{
int Attr { get; }
}
interface IWriteOnly
{
int Attr { set; }
}
interface I : IReadOnly, IWriteOnly
{
}
class CReadOnly : IReadOnly
{
protected int _Attr;
public int Attr
{
get { return _Attr; }
}
}
class C : CReadOnly, I
{
public int Attr
{
get { return base.Attr; }
set { _Attr = value; }
}
}
EDIT: I changed the get portion of the C.Attr property to be return base.Attr instead of return _Attr; in order to be more consistent with the code example in the original question. I also think that is more correct, since you may have more complicated logic defined in CReadOnly.Attr that you do not want to duplicate.
Some of the interfaces and classes have been renamed from the original example. "I" became "IReadOnly", and "IWithSet" became "I". "C" became "CReadOnly", and "CWithSet" became "C".
This compiled for me with no warnings.
EDIT: This compiled for me with no warnings regarding the interface members. I did get 1 warning regarding the C class' Attr property hiding the CReadOnly class' property, but this should be entirely expected, since hiding/shadowing is what's going on in my example. One weird thing: I could swear that I compiled (and ran!) this code a couple of times and saw 0 warnings. That confused me at the time, but I let it go...yet now I'm seeing the 1 warning as I would expect. Maybe just a compiler glitch.
If you want separate attributes with the same name, use new. The warning is self explanatory.
On the other hand, what you want seems to be more like:
#pragma warning disable CS0108
interface IWithSet : I
{
int attr { get; set; }
}
#pragma warning restore CS0108
Possibly not perfect, but one solution could be:
interface IWithSet : I
{
void SetAttr(int value);
}
How about just:
interface IWithSet : I
{
new int attr { get; set; }
}
The downside is IWithSet will always have both getter and setter even if the getter in 'I' is removed:
interface I { }
If you're defining the two interfaces with the assumption that 'I' will always have the getter then there's nothing wrong with this approach, this will work fine in an interface hierarchy designed to restrict access rather than encapsulate logic specific to a layer of abstraction (like a typical reader/writer type structure where the writer inherits all of the reader's access on the SAFE assumption that the reader has read permission!).

Why is it impossible to override a getter-only property and add a setter? [closed]

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'.

Categories