Overriding a read/write property to make it readonly - c#

I'm writing a custom control in C# based on TextBox. I want the Text property of my control to be read-only (since only certain values are allowed in the textbox and I don't want the calling program to be able to put invalid values in there.)
I don't see how to do this. If I use public override Text {} the compiler inserts default get and set accessors. If I comment out the set accessor, the code compiles and runs, which I assume means the base accessor is being used. If I put readonly in the definition of my property, the compiler throws an error.
Any help would be greatly appreciated.

The issue here is that by trying to make a read/write property read-only, you're violating the contract of your base class. Your base class explicitly states that this property can be both retrieved and modified. Derived classes cannot break the contracts of their base classes, otherwise polymorphism would fail. Remember that if B derives from A, anywhere an A object is accepted, B must perform.
If that should not be the case for the derived class, then I would first question the design -- should this truly be derived from the base class? Is this truly an "is-a" relationship?
Assuming that we passed that test and truly should be derived, one approach -- which I don't personally like, but will share anyway -- may be to simply have the setter throw an exception. I personally don't like this, it still violates the contract, and feels like an excessive amount of cognitive friction in using your derived class, but if you truly have that solid a reason to do so ... well ... OK, I guess. But be sure you know WHY you're hacking around this.
But go back to the first point: Is this truly a scenario where a derived class is the right answer, from a design standpoint? Without seeing your code, my gut reaction is a no.
EDIT
Somehow in my initial read of this, I missed the fact that we're talking about a UI control here. I stand by what I wrote above this edit, in the general property overriding case. However, in the case of a UI control, where the polymorphism opportunities (I hope) will be somewhat limited, and where the need may well justify this design, then my recommendation would be to have the Text property setter throw an exception.
A better design, in my opinion, would be composition. Make a user control, add the TextBox to the user control design surface with Dock=Fill, and then expose a new Text property which is readonly. You can also now expose only those properties you really want to.

You have to hide the base property by declaring Text with the "new" keyword.
public new string Text { get; private set;}
You can't change access rights with an override, so you cannot use the override keyword, as you've seen. This way will "hide" the base implementation of Text, which isn't always a good idea, but as long as you know the risks it will work for you.

public new string Text { get; private set;}

Aside from others comments on overall design issues (which John Ruby explains nicely), you could always just override the setter to do nothing or throw an exception.

I don't think that shadowing the property is the right answer, because any reference through the base will still work. Since the property is virtual, you can override it and implement a setter that ignores changes or throws an exception. I know it seems less clean, but it has the advantage of actually working.
edit
Looks like Yuriy Faktorovich made the same suggestion before I could.

I think John Rudy may have a point here. Inheritance is not the answer to everything. If what you need to do is restrict a textbox so that only valid values can be accepted then perhaps you want to use a validation control to make sure that only certain values are allowed.
This way you get the behaviour you want by making use of the components Microsoft have provided us with. No inherited class necessary.
Edit: If you create a subclass every time you want to modify the behaviour of a UI control you will quickly have an unruly inheritance hierarchy on your hands. For this reason I would suggest you consider composition to modify UI controls.

Related

What does the Auto Property give me over a simple Field? [duplicate]

We're often told we should protect encapsulation by making getter and setter methods (properties in C#) for class fields, instead of exposing the fields to the outside world.
But there are many times when a field is just there to hold a value and doesn't require any computation to get or set. For these we would all do this number:
public class Book
{
private string _title;
public string Title
{
get => _title;
set => _title = value;
}
}
Well, I have a confession, I couldn't bear writing all that (really, it wasn't having to write it, it was having to look at it), so I went rogue and used public fields.
Then along comes C# 3.0 and I see they added automatic properties:
public class Book
{
public string Title { get; set; }
}
Which is tidier, and I'm thankful for it, but really, what's so different than just making a public field?
public class Book
{
public string Title;
}
In a related question I had some time ago, there was a link to a posting on Jeff's blog, explaining some differences.
Properties vs. Public Variables
Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
You can't databind against a variable.
Changing a variable to a property is a breaking change. For example:
TryGetTitle(out book.Title); // requires a variable
Ignoring the API issues, the thing I find most valuable about using a property is debugging.
The CLR debugger does not support data break points (most native debuggers do). Hence it's not possible to set a break point on the read or write of a particular field on a class. This is very limiting in certain debugging scenarios.
Because properties are implemented as very thin methods, it is possible to set breakpoints on the read and write of their values. This gives them a big leg up over fields.
Changing from a field to a property breaks the contract (e.g. requires all referencing code to be recompiled). So when you have an interaction point with other classes - any public (and generally protected) member, you want to plan for future growth. Do so by always using properties.
It's nothing to make it an auto-property today, and 3 months down the line realize you want to make it lazy-loaded, and put a null check in the getter. If you had used a field, this is a recompile change at best and impossible at worst, depending on who & what else relies on your assemblies.
Just because no one mentioned it: You can't define fields on Interfaces. So, if you have to implement a specific interface which defines properties, auto-properties sometimes are a really nice feature.
A huge difference that is often overlooked and is not mentioned in any other answer: overriding. You can declare properties virtual and override them whereas you cannot do the same for public member fields.
It's all about versioning and API stability. There is no difference, in version 1 - but later, if you decide you need to make this a property with some type of error checking in version 2, you don't have to change your API- no code changes, anywhere, other than the definition of the property.
Another advantage of auto-implemented properties over public fields is that you can make set accessors private or protected, providing the class of objects where it was defined better control than that of public fields.
There is nothing wrong in making a field public. But remember creating getter/setter with private fields is no encapsulation. IMO, If you do not care about other features of a Property, you might as well make it public.
Trivial properties like these make me sad. They are the worst kind of cargo culting and the hatred for public fields in C# needs to stop. The biggest argument against public fields is future-proofing: If you later decide you need to add extra logic to the getter and setter, then you will have to do a huge refactor in any other code that uses the field. This is certainly true in other languages like C++ and Java where the semantics for calling a getter and setter method are very different from those for setting and getting a field. However, in C#, the semantics for accessing a property are exactly the same as those for accessing a field, so 99% of your code should be completely unaffected by this.
The one example I have seen of changing a field into a property actually being a breaking change at the source level is something like:
TryGetTitle(out book.Title); // requires a variable
To this I have to ask, why TF are you passing some other class's field as a reference? Depending on that not being a property seems like the real coding failure here. Assuming that you can directly write to data in another class that you know nothing about is bad practice. Make your own local variable and set book.Title from that. Any code that does something like this deserves to break.
Other arguments I have seen against it:
Changing a field to a property breaks binary compatibility and requires any code that uses it to be recompiled: This is a concern iff you are writing code for distribution as a closed-source library. In that case, yes, make sure none of your user-facing classes have public fields and use trivial properties as needed. If however you are like 99% of C# developers and writing code purely for internal consumption within your project, then why is recompilation a big concern? Just about any other change you make is going to require recompilation too, and so what if it does? Last I checked, it is no longer 1995, we have fast computers with fast compilers and incremental linkers, even larger recompilations shouldn't need more than a few minutes, and it has been quite some time since I have been able to use "my code's compiling" as an excuse for swordfighting through the office.
You can't databind against a variable: Great, when you need to do that, make it into a property.
Properties have features that make them better for debugging like reflection and setting breakpoints: Great, one you need to use one of those things, make it into a property. When you're done debugging and ready to release, if you don't still need those functionalities, change it back into a field.
Properties allow you to override behavior in derived classes: Great, if you are making a base class where you think such a scenario is likely, then make the appropriate members into properties. If you're not sure, leave it as a field and you can change it later. Yes, that will probably require some recompilation, but again, so what?
So in summary, yes there are some legitimate uses for trivial properties, but unless you are making a closed source library for public release, fields are easy enough to convert into properties when needed, and an irrational fear of public fields is just some object oriented dogma that we would do well to rid ourselves of.
For me, the absolute deal breaker for not using public fields was the lack of IntelliSense, showing the references:
Which is not available for fields.
If you decide later to check that the title is unique, by comparing to a collection or a database, you can do that in the property without changing any code that depends on it.
If you go with just a public attribute then you will have less flexibility.
The extra flexibility without breaking the contract is what is most important to me about using properties, and, until I actually need the flexibility, auto-generation makes the most sense.
One thing you can do with Fields but not with Properties (or didn't used to be able to ... I'll come to that in a moment) is that Fields can be designated as readonly whereas Properties cannot. So Fields give you a clear way of indicating your intention that a variable is there to be set (from within the constructor) at object-instantiation time only and should not be changed thereafter. Yes, you can set a Property to have a private setter, but that just says "this is not to be changed from outside the class", which is not the same as "this is not to be changed after instantiation" - you can still change it post-instantiation from within the class. And yes you can set the backing field of your property to be readonly, but that moves post-instantiation attempts to change it to being run-time errors rather than compile-time errors. So readonly Fields did something useful which Properties cannot.
However, that changes with C# 9, whereby we get this helpful syntax for Properties:
public string Height { get; init; }
which says "this can get used from outside of the class but it may only be set when the object is initialized", whereupon the readonly advantage of Fields disappears.
One thing I find very useful as well as all the code and testing reasons is that if it is a property vs a field is that the Visual Studio IDE shows you the references for a property but not a field.
My pov after did some researches
Validation.
Allow overriding the accessor to change the behaviour of a property.
Debugging purpose. We'll be able to know when and what the property change by setting a breakpoint in the accessor.
We can have a field set-only. For instance, public set() and private get(). This is not possible with the public field.
It really gives us more possibility and extensibility.

What is the point of empty getters and setters, and thus the point of auto generating getters and setters in c#

I sometimes use {get; set;} in c# becuase I am told that sometimes technologies I am working with require them (linq2sql?)
I'm wondering why sometimes a technology may require a private field with a getter and setter (and thus the shorthand is a nice shortcut) rather than a public field.
I understand that having logic within a getter or setter makes sense, but not so sure on the point of empty ones?
Is the answer the same as this post, if so just tell me so!
What is exactly the point of auto-generating getters/setters for object fields in Scala?
One reason is Inheritance as your link already points out
One other benefit I can think of is that you can make properties read only by exposing them through public getter. You cannot do this with fields
public String ReadOnlyString {get; private set;}
The point is that it it's bad encapsulation to expose private members to users of your class. By using a property, you can expose the information in a way that allows you to change the internal implementation or storage of that value without the interface changing.
E.g. If you decided to store an integer as a byte to save memory internally, then all calling code would have to be recompiled. This is inconvenient even if you own all the source code, but extremely inconvenient if your code us I a library that somebody else is using.
Another common example is that you may later wish to raise an event if the value is changed.
Other reasons are that some clients may look for properties via reflection, but will not look for member fields - for example, the forms editor and property grids do this.
Also, you can make properties virtual, which can't be done with fields.
Or to look at it from another point of view, what reasons can you think of to_not_ use properties.

Fields vs Properties for private class variables [duplicate]

This question already has answers here:
Are there any reasons to use private properties in C#?
(19 answers)
Closed 9 years ago.
For private class variables, which one is preferred?
If you have a property like int limit, you want it to be:
int Limit {get; set;}
and use it inside the class, like so:
this.Limit
Is there a reason to use it or not use it? Maybe for performance reasons?
I wonder if this is a good practice.
For a private member, I only make it a property when getting and/or setting the value should cause something else to occur, like:
private int Limit
{
get
{
EnsureValue();
return this._limit;
}
}
Otherwise, fields are fine. If you need to increase their accessibility, it's already a big enough change that making it a property at that point isn't a huge deal.
Edit: as Scott reminds us in the comments, side effects in properties can often cause more pain than anything else. Don't violate Single Responsibility and limit property logic to consistent, logical operations on the value only that must be done at the gate - such as lazy loading (as in the example above), transforming an internal structure into a publicly-useful format, etc.
The only real benefit an auto-property has over a field when the accessibility is private is that you can set a breakpoint on accesses and updates of the variable. If that is important to your scenario then definitely use an auto-property. Otherwise, given there is no substantial advantage, I choose to go with the simplest construct which is a field.
I would say its good practice to use a property. If ever you had to expose the limit value and used a local member it will require more coding while if its a property it would only require a change of its modifier.
I think it's cleaner also.
Granted, since it's a private API, its an implementation detail - you can do whatever you want here. However, there is very little reason to not use a property, even for private classes. The properties get inlined away by the JIT, unless there is extra code in place, so there isn't really a performance impact.
The biggest reasons to prefer properties, IMO, are:
Consistency in your API - You'll want properties in publicly exposed APIs, so making them in the private API will make your programming exprience more consistent, which leads to less bugs due to better maintainability
Easier to convert private class to public
From my perspective, using properties in lieu of variables boils down to:
Pros
Can set a break point for debugging, as Jared mentioned,
Can cause side-effects, like Rex's EnsureValue(),
The get and set can have different access restrictions (public get, protected set),
Can be utilized in Property Editors,
Cons
Slower access, uses method calls.
Code bulk, harder to read (IMO).
More difficult to initialize, like requiring EnsureValue();
Not all of these apply to int Limit {get; set;} style properties.
The point of automatic properties is they are very quick at creating a public access to some field in your class. Now, they offer no benefit over exposing straight up fields to the outside world, other than one big one.
Your class' interface is how it communicates with the outside world. Using automatic properties over fields allows you to change the internals of your class down the road in case you need to make setting the value of that property do something or check authorization rules or something similar on the read.
The fact that you already have a property means you can change your implementation without breaking your public interface.
Therefore, if this is just a private field, an automatic property isn't really that useful, not only that, but you can't initialize public properties at declaration like you can with fields.
I generally follow the following principle: If it's for strictly private use, use a field as it is faster.
If you decide that it should become public, protected or internal some day, it's not difficult to refactor to a property anyway, and with tools like ReSharper, it takes about 3 seconds to do so... :)
There's nothing wrong with having private or protected properties; this is mostly useful when there is some rule or side effect associated with the underlying variable.
The reason why properties seem more natural for public variables is that in the public case, it is a way to hedge one's bet against future implementation changes, whereby the property will remain intact but the implementation details somehow move around (and/or some additional business rule will be needed).
On performance, this is typically insignificant, or indeed identical for straight-assignment properties.
I personally dislike (but often use) plain assignment properties because they just clutter the code. I wish C# would allow for "after the fact refactoring".
Properties provide some very good automatic features (like Json and Xml Serialization)
Fields do not.
Properties can also be a part of an Interface. If you decide to refactor later on... this might be something to consider too.
Properties are just syntactic sugar, C# will compile them into get_PropertyName and set_PropertyName, so performance differences are not a consideration.
If your data member need only set and get logic then properties are very good and fast solution in C#

Why prefer Properties to public variables? [duplicate]

This question already has answers here:
Closed 13 years ago.
Other being able to sanity check values in a setter is there a more underlying reason to prefer properties to public variables?
We've had this subject before but I can't find anything now.
In brief: your needs might change: where there's no sanity check now, one might be required in the future. However, if you change your public fields to properties, this breaks binary compatiblity: every client who uses your code/library would have to re-compile.
This is bad because it potentially costs a lot of money.
Using properties from the beginning avoids this problem. This even counts for code that is not part of a library. Why? Because you never know: the code (even if highly domain-specific!) might prove useful so you want to refactor it to a library. This refactoring process is obviously made much easier if you are already using properties in place of public/protected fields.
Additionally, writing public properties is easy in C# 3.0 because you can just use the auto-implemented properties, saving you quite a bit of code:
public DataType MyProperty { get; set; }
Will implement the necessary backing field and getter/setter code for you.
I will add a personal note: .NET's behaviour in this regard is somewhat lazy. The compiler could just change public fields to properties on the fly, thus avoiding the problem. VB6 already did this for COM-exposed classes and I see absolutely no reason for VB.NET and C# not to do the same. Perhaps someone on the compiler teams (Jared?) could comment on this.
In a nutshell:
You can control acces (readonly,
writeonly, read/write)
You can validate values when setting
a property (check for null etc)
You can do additional processing,
such as lazy initialization
You can change the underlying
implementation. For example, a
property may be backed by a member
variable now, but you can change it
to be backed by a DB row without
breaking any user code.
Jeff Atwood has blogged about it:
There are valid reasons to make a trivial property, exactly as depicted above:
Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
You can't databind against a variable.
Changing a variable to a property is a breaking change.
It's a shame there's so much meaningless friction between variables and properties; most of the time they do the exact same thing. Kevin Dente proposed a bit of new syntax that would give us the best of both worlds:
public property int Name;
However, if the distinction between variable and property is such an ongoing problem, I wonder if a more radical solution is in order. Couldn't we ditch variables entirely in favor of properties? Don't properties do exactly the same thing as variables, but with better granular control over visibility?
Changing a field to a property in the future is considered a breaking change. Fields are considered implementation details of classes and exposing them publicly breaks encapsulation.
Use of properties makes your code more object oriented. By making member variables public, you are exposing your implementation.
Also see this link from C#'s Programming Guide
You can also protect write access and allow read access with a property:
public int Version { get; private set; }
If you work in a closed environment -- you dont develop a SDK, all classes are used within a same project framework -- there is no difference.
The usual argument is that "in the future you may need to do some check on the values, so it is easier with properties". I dont buy it at all.
Using public fields is more readable, less decoration and easier to use.
Yes.
Consider a public varibale which now holds a string, you can simply set it. However, if you decide that that public variable should hold an object which should be initialized with a string then you would have to change all your code using your original object. But if you would have used setter you would only have to change the setter to initialize the object with the provided string.

Why aren't classes sealed by default?

I was just wondering, since the sealed keyword's existence indicates that it's the class author's decision as to whether other classes are allowed to inherit from it, why aren't classes sealed by default, with some keyword to mark them explicitly as extensible?
I know it's somewhat different, but access modifiers work this way. With the default being restrictive and fuller access only being granted with the insertion of a keyword.
There's a large chance that I haven't thought this through properly, though, so please be humane!
I'd say it was just a mistake. I know many people (including myself) who believe that classes should indeed be sealed by default. There are at least a couple of people in the C# design team in that camp. The pendulum has swung somewhat away from inheritance since C# was first designed. (It has its place, of course, but I find myself using it relatively rarely.)
For what it's worth, that's not the only mistake along the lines of being too close to Java: personally I'd rather Equals and GetHashCode weren't in object, and that you needed specific Monitor instances for locking too...
In my opinion there should be no default syntax, that way you always write explicitly what you want. This forces the coder to understand/think more.
If you want a class to be inheritable then you write
public extensible class MyClass
otherwise
public sealed class MyClass
BTW I think the same should go with access modifiers, disallow default access modifiers.
Inheritance is a foundational principle of OO, so arguably, disallowing it by default wouldn't be intuitive.
You could probably make just as many arguments in favor of sealed-by-default as you could against it. If it were the other way around, someone would be posting the opposite question.
I can't recall having heard a rationale for the decision to have classes not sealed by default. However, there are certainly quite a few people who believe that C# should have been spec'ed to have sealed be the default:
http://codebetter.com/blogs/patricksmacchia/archive/2008/01/05/rambling-on-the-sealed-keyword.aspx
sealed classes prevent inheritance and therefore are an OO abombination. see this rant for details ;-)
80% of the features of Word go unused. 80% of classes don't get inherited from. In both cases, once in a while, someone comes along and wants to use or reuse a feature. Why should the original designer prohibit reuse? Let the reuser decide what they want to reuse.
Merely deriving from an unsealed class doesn't change the class's behavior. The worst that can happen is that a new version of the base class will add a member with the same name as the deriving class (in which case there will just be a compiler warning saying you should use the new or override modifier) or the base class is sealed (which is a design no-no if the class has already been released into the wild). Arbitrary sublassing still complies with the Liskov Substitution Principle.
The reason that members are not overridable by default in C# is that because overriding a method can change the base class's behaviour in a way that the base class's author didn't anticipate. By making it explicitly abstract or virtual, it's saying that the author is aware that that it can change or is otherwise beyond their control and the author should have taken this into account.
For the same reason why objects are not private by default
or
to be consistent with the object analogue, which is objects are not private by default
Just guessing, coz at the end of the day it's a language's design decision and what the creators say is the canon material.

Categories

Resources