How do I keep extensibility with private properties? - c#

I'm working on the following class. I've shortened the list of properties as an example.
public class Paycheck
{
public decimal Gross { get; private set; }
public decimal FederalWithholdingTax { get; private set; }
public decimal StateWithholdingTax { get; private set; }
// ...
}
Now my idea was to create an interface to calculate all the taxes...
public interface IPaycheckDeductionCalculator
{
void Calculate();
}
The idea after that is to create methods outside of the Paycheck class that can perform calculations/deductions. With the way laws and payroll processes work, how deductions are performed and what deductions are performed are constantly changing, so I want to keep extensibility easy.
My dilemma is that I want to keep the Paycheck property setters private so that just anyone can change those values. Keeping that data constant after a paycheck is processed is critical.
I considered the use of delegates, but I'm not so sure that's my answer either, as I still wouldn't be able to develop the desired methods outside of the Paycheck class.
Is there something I'm not thinking of or is this a "you can't have your cake and eat it too" kind of situation?

Have the interfaces that calculate these values return the values that they are calculating. Pass in instances of these interfaces to Paycheck, which can the perform the calculations (without needing to know anything about the implementation of the interface) and then have it set the values of the appropriate properties.

Related

Can I prevent a private variable from being changed by other objects of the same class?

I'm multithreading a real-time game, and would like to prevent the state variables of objects on one thread from being set from another thread. This will make preventing race conditions a lot easier.
I would still like to be able to read the state of other objects, however. I'm intending to use a double buffer system, where one state object is used as the forebuffer and makes state changes while the other is used as the backbuffer and provides the (previous frame's) state to other objects. I need to be able to read state information from the backbuffer to make changes in the forebuffer.
The issue is that even if the variables setter is private, it's possible to change it from another object of the same class.
public class State
{
//Some example state information
public string StateVar1 { get; private set; }
//This method will be farmed out to multiple other threads
public void Update(State aDifferentStateObject)
{
StateVar1 = "I want to be able to do this";
string infoFromAnotherObject = aDifferentStateObject.StateVar1; //I also want to be able to do this
aDifferentStateObject.StateVar1 = "I don't want to be able to do this, but I can";
}
}
May not be the most direct solution, but one way to protect the properties is to use an interface.
public interface IState
{
string StateVar1 { get; }
}
public class State:IState
{
//Some example state information
public string StateVar1 { get; private set; }
//This method will be farmed out to multiple other threads
public void Update(IState aDifferentStateObject)
{
StateVar1 = "I want to be able to do this"; // Allowed
string infoFromAnotherObject = aDifferentStateObject.StateVar1;
aDifferentStateObject.StateVar1 = "I don't want to be able to do this, but I can"; // NOT allowed
}
}
If you're writing a class, it's assumed that you'll make the class work the way you want it to work. The purpose of making stuff private is to prevent your co-workers (or clients) from breaking your class's concerns while they work on their own classes/functions/modules.
Saying "I don't want to be able to do this thing." is somewhat missing the point.
That said, the thing that's nice about less permissive languages in general is that they prevent your co-workers from writing crappy or non-idiomatic code. The other answers show idioms you could use that would make it harder for your peers to later edit break your nice elegant pattern. Anu Viswan's get's my vote.
add field this0=this and in the setter, check that this==this0.
it's possible to change it from another object of the same class.
You cannot stop your own class from setting private setters.
I mean after all, you are the author of that class, its only your fingers you have to worry about.
public class SomeOtherNonRelatedClass
{
public void Update(State aDifferentStateObject)
{
// the world is as it should be
aDifferentStateObject.StateVar1 = "bang!!!" // compiler error
}
}
If you would like to prevent your self from changing your own member, then use an extension method
public class Extensions
{
public void Update(this State aDifferentStateObject)
{
// the world is as it should be
aDifferentStateObject.StateVar1 = "bang!!!" // compiler error
}
}
or make it truly read only (though is probably not useful)
public string StateVar1 { get; }
or a backing field, so you can set it internally
private string backingField;
public string StateVar1
{
get => backingField;
}

where to put the checking function for the model (asp.net mvc5)

i know the model should not have any logic , but i don't know where is the good place to put the checking or the update function for a particular model
ex.
public class GuestBook
{
public int money { get; set; }
[Required]
public string name { get; set; }
[Required]
public string email { get; set; }
public DateTime content { get; set; }
public bool rich()
{
if (this.money <3000)
return false;
else
return true;
}
public void earn(GuestBook b)
{
this.money += b.money;
}
}
the function rich() and earn() is only use for this module(GuestBook)
if i didn't put it in this module , then where i should put?
Following good OOP design principles, the only way to really protect your classes' invariants (and not have a maintainability nightmare) is by not allowing them to be changed by anyone other than the class. Typically this is done by NOT exposing public setter methods (public auto properties are evil), making your fields readonly (wherever possible), and initializing them from the constructor.
The whole point of having classes is to group data with behavior. A simple data structure containing ints and strings is not a class in the OOP sense, it's just a struct.
In some cases you are stuck with an even more evil ORM that FORCES you to make all properties public. This is not an issue with Entity Framework (and some others too) though, EF can magically reflect in and access private setters if needed, you just gotta make sure there's also a private default constructor.
According to your class rich method is validating and earn method is applying business logic. You can create AdditionalMetadataAttribute for rich method logic that can fire on ModelState.IsValid and for earn method you need to create BO class that apply your all business logic.
here a link for AdditionalMetadataAttribute

Best design pattern for refactoring a class that does calculation based on many parameters

I'm refactoring a set of classes as below which does some price calculations.
the calculation is done based on many parameters.
The code is :
public interface IParcel {
int SourceCode { get; set; }
int DestinationCode { get; set; }
int weight{get;set;}
decimal CalculatePrice();
}
public abstract class GeneralParcel : IParcel {
//implementation of inteface properties
//these properties set with in SourceCode & DestinationCode
//and are used in CalculatePrice() inside classes that inherit from GeneralParcel
protected SourceProvinceCode{get; protected set;}
protected DestinationProvinceCode{get;protected set;}
//private variables we need for calculations
private static ReadOnlyDictionary<int, List<int>> _States_neighboureness;
private static ReadOnlyCollection<City> _Citieslist;
private static ReadOnlyCollection<Province> _Provinceslist;
protected ReadOnlyCollection<City> Citieslist {get { return _Citieslist; }}
protected ReadOnlyCollection<Province> ProvincesList {get { return _Provinceslist; }}
protected ReadOnlyDictionary<int, List<int>> StatesNeighboureness {get {return _States_neighboureness; }}
//constructor code that initializes the static variables
//implementation is in concrete classes
public abstract decimal CalculatePrice();
}
public ExpressParcel : GeneralParcel {
public decimal CalculatePrice() {
//use of those three static variables in calculations
// plus other properties & parameters
// for calculating prices
}
}
public SpecialParcel : GeneralParcel {
public decimal CalculatePrice() {
//use of those three static variables in calculations
// plus other properties & parameters
// for calculating prices
}
}
Right now, the code uses "Strategy pattern" efficiently.
my question is that those three static properties, really are not part of parcel object, they are need only for price calculations, so which design pattern or wrapping(refactoring), is suggested?
Is having another interface as below necessary (& then wrap those static properties inside it?, even make static that class, because it is basically only some calculations), then how to connect it to IParcel?
Doing so, how to implement CalculatePrice() in SpecialParcel & ExpressParcel classes?
public interface IPriceCalculator {
decimal CalculatePrice();
}
EDIT: the above was only a big picture of all system, there is also other consideration that in comments, we discus about them, and i write them here again for clearing things .
there is BulkDiscount for all of ParcelTypes. bulk post happens when customer send more than 10 parcels(or any threshold), also there is special discount when one customer send more than 10 parcel to a unique destination(there is only one receiver). now this type of discounts are managed in each parcel type's CalculatePrice(). even there are discount for blinds for under 7Kg parcels.
also right now there are 3 parceltype, i show only 2 of them here. but we need to add other type in future(TNT & DHL support).
each type has many services that customer can select and pay for it.
for example, sms service or email service & so on.
Personally, while others might say that a Parcel shouldn't know how to calculate its own shipping cost, I disagree. Your design already identifies that there are three different kinds of parcel with three different calculations, so to my (naive?) eyes it's entirely appropriate that the object should have a method e.g. CalculatePrice().
If you really want to go that way, then you'd need two implementations of IParcelPriceCalculator (or whatever you call it) and an abstract factory method on the GeneralParcel to create the concrete ExpressParcelPriceCalculator or SpecialParcelPriceCalculator classes. Which, personally, I'd consider overkill, not least as that code will then be tightly coupled to each GeneralParcel implementation anyway.
I would however consider making the static collections of City and Province public static properties of City and Province respectively. That's just tidier, and it's where I'd expect to find them if I were maintaining the code. StatesNeighbourliness should probably go into Province, or it might even justify its own class.
The way in which you calculate a price for a given parcel is a responsibility that shouldn't belong to a data object.
Given what you've told me, here is how I would implement, to try and account for future considerations:
public interface IParcel {
int SourceCode { get; set; }
int DesinationCode { get; set; }
int Weight { get; set; }
}
public class PricingCondition {
//some conditions that you care about for calculations, maybe the amount of bulk or the date of the sale
//might possibly be just an enum depending on complexity
}
public static class PricingConditions {
public static readonly PricingCondition FourthOfJulyPricingCondition = new PricingCondition();
public static readonly PricingCondition BulkOrderPricingCondition = new PricingCondition();
//these could alternatively come from a database depending on your requirements
}
public interface IParcelBasePriceLookupService {
decimal GetBasePrice(IParcel parcel);
//probably some sort of caching
}
public class ParcelPriceCalculator {
IParcelBasePriceLookupService _basePriceLookupService;
decimal CalculatePrice(IParcel parcel, IEnumerable<PricingCondition> pricingConditions = new List<PricingCondition>()) {
//do some stuff
}
decimal CalculatePrice(IEnumerable<IParcel> parcels, IEnumerable<PricingCondition> pricingConditions = new List<PricingCondition>()) {
//do some stuff, probably a loop calling the first method
}
}
The IPriceCalculator would be best practice for Single Responsibility Principle.
But change the method's signature to decimal CalculatePrice(IParcel parcel);
The method is calling IParcel's CalculatePrice() method to get base price for each parcel.
The advice I'd offer would depend to a degree on how you go about generating and using the Parcel polymorphs. What I mean is, we can't see what criteria are used to determine whether something is "Express" or "Special" and whether those criteria have to do with the properties of the parcel itself or some external factor.
Having said that, I think your intuition is a good one about separating the price calculation from the Parcel object itself. As kmkemp pointed out, a parcel shouldn't be figuring out how to calculate the price of a parcel depending on what type of parcel it is. A parcel is a data transfer/POCO type object, at least as indicated in your giving it a weight, source, etc.
However, I'm not clear on why you're using these interfaces. Don't get me wrong -- interfacing is nice for decoupling and testability, but why is there a parcel interface in addition to an abstract base class with an abstract method. Personally, going on just the information that I have, I'd do this:
public class Parcel
{
int SourceCode { get; set; }
int DestinationCode { get; set; }
int weight { get; set; }
}
public abstract class GeneralCalculator
{
//Statics go here, or you can inject them as instance variables
//and they make sense here, since this is presumably data for price calculation
protected static ReadOnlyDictionary<int, List<int>> _States_neighboureness;
protected static ReadOnlyCollection<City> _Citieslist;
protected static ReadOnlyCollection<Province> _Provinceslist;
//.... etc
public abstract Decimal CalculatePrice(Parcel parcel);
}
public class ExpressCalculator : GeneralCalculator
{
public override decimal CalculatePrice(Parcel parcel)
{
return 0.0M;
}
}
public class SpecialCalculator : GeneralCalculator
{
public override decimal CalculatePrice(Parcel parcel)
{
return 0.0M;
}
}
But, again, I don't know how the parcels are actually being processed. You may need some kind of modification to this concept depending on how you generate and then process the parcels. For instance, if the kind of parcel it is depends on the property values of the parcel, you might want to define a factory method or class that takes a parcel and returns an appropriate instance of the calculator.
But, however you modify it, I'd definitely cast my vote for your thought of decoupling the definition of the parcel from the scheme for calculating its price. Data storage and data processing are separate concerns. I'd also not vote in favor of a static class somewhere containing global settings, but that's my own personal taste -- that kind of thing too easily acquires a setter and becomes a global variable down the road.
Like you say, those static properties aren't really part of the GeneralParcel class. Move them to a static "ListsOfThings" class.
Then you can use code that refers to ListsOfThings.ProvincesList, etc.

Appropriate design/design pattern for this problem?

I previously posted this, but I guess it was too verbose and irrelevant. My question is also like this. One poster in the second link said the answer (of why you can't do the code below) was a problem of design, specifically "bad use of inheritance". So I'd like to check this issue again with the experts at StackOverflow and see if this is really an issue of "bad inheritance" - but more importantly, how to fix the design.
Like the poster, I'm also confused about the Factory method and how I can apply it. It seems the factory method is for multiple concrete classes that have the exact same implementation as the abstract base class and do not add their own properties. But, as you will see below, my concrete classes build upon the abstract base class and add extra properties.
The Base Class We Build Upon:
public abstract class FlatScreenTV
{
public string Size { get; set; }
public string ScreenType { get; set; }
}
Extension Class Examples:
public class PhillipsFlatScreenTV : FlatScreenTV
{
// Specific to Phillips TVs. Controls the backlight intensity of the LCD screen.
public double BackLightIntensity { get; set; }
}
public class SamsungFlatScreenTV : FlatScreenTV
{
// Specific to Samsung TVs. Controls the time until the TV automatically turns off.
public int AutoShutdownTime { get; set; }
}
Let's say there are more extension classes for more brands of flat screen TVs. And then, let's say we stick them all into a generic List:
public static void Main()
{
List<FlatScreenTV> tvList = new List<FlatScreenTV>();
tvList.Add(new PhillipsFlatScreenTV());
tvList.Add(new SamsungFlatScreenTV());
tvList.Add(new SharpFlatScreenTV());
tvList.Add(new VizioFlatScreenTV());
FlatScreenTV tv = tvList[9]; // Randomly get one TV out of our huge list
}
The Problem:
I want to access the specific properties of whatever 'original' brand TV this variable belongs to. I know the brand because if I call tv.GetType(), it returns the correct 'original' type - not FlatScreenTV. But I need to be able to cast tv from FlatScreenTV back to its original type to be able to access the specific properties of each brand of flat-screen TVs.
Question #1: How can I dynamically cast that, properly - without makeshift hacks and huge if-else chains to brute-guess the 'original' type?
After browsing around similar design issues, most answers are: you can't. Some people say to look at the Factory Pattern, and others say to revise the design using interfaces, but I don't know how to use either to solve this problem.
Question #2: So, how should I design these classes so that I can access the original type's specific properties in the context above?
Question #3: Is this really bad inheritance?
Your design violates the "Liskov Substitution Principle". In other words, the code that deals with items from your list of FlatScreenTV shouldn't know or care what derived type is.
Say your code needs to create a custom remote control GUI. It might be enough to simply know the names and types of the properties of each TV to auto-generate the UI. In which case you could do something like this to expose the custom properties from the base class:
public abstract class FlatScreenTV
{
public FlatScreenTV()
{
CustomProperties = new Dictionary<string,object>();
}
public Dictionary<string,object> CustomProperties { get; private set; }
public string Size { get; set; }
public string ScreenType { get; set; }
}
public class PhillipsFlatScreenTV : FlatScreenTV
{
public PhillipsFlatScreenTV()
{
BackLightIntensity = 0;
}
// Specific to Phillips TVs. Controls the backlight intensity of the LCD screen.
public double BackLightIntensity
{
get { return (double)CustomProperties["BackLightIntensity"]; }
set { CustomProperties["BackLightIntensity"] = value; }
}
}
public class SamsungFlatScreenTV : FlatScreenTV
{
public SamsungFlatScreenTV()
{
AutoShutdownTime = 0;
}
// Specific to Samsung TVs. Controls the time until the TV automatically turns off.
public int AutoShutdownTime
{
get { return (int)CustomProperties["AutoShutdownTime"]; }
set { CustomProperties["AutoShutdownTime"] = value; }
}
}
If you really do need to be working directly with the derived types, then you should instead consider moving to a plugin based architecture. For example, you might have a factory method like this:
IRemoteControlGUI GetRemoteControlGUIFor(FlatScreenTV tv)
which would scan your plugins and find the one that knew how to build the UI for the particular type of FlatScreenTV you passed in. This means that for every new FlatScreenTV you add, you also need to create a plugin that knows how to make its remote control GUI.
Factory Pattern would be the best way to go
I can offer a partial answer:
Firstly read up on Liskov's Substitution Principle.
Secondly you are creating objects that inherit from FlatScreenTV, but apparently for no purpose as you want to refer to them by their SubType (SpecificTVType) and not their SuperType (FlatScreenTV) - This is bad use of Inheritance as it is NOT using inheritance lol.
If your code wants to access properties particular to a given type, then you really want this code encapsulated within that type. Otherwise everytime you add a new TV type, all the code that handles the TV list would need to be updated to reflect that.
So you should include a method on FlatScreenTV that does x, and override this in TV's as required.
So basically in your Main method above, instead of thinking I want to be dealing with TVTypeX, you should always refer to the basetype, and let inheritance and method overriding handle the specific behaviour for the subtype you are actually dealing with.
Code eg.
public abstract class FlatScreenTV
{
public virtual void SetOptimumDisplay()
{
//do nothing - base class has no implementation here
}
}
public class PhilipsWD20TV
{
public int BackLightIntensity {get;set;}
public override void SetOptimumDisplay()
{
//Do Something that uses BackLightIntensity
}
}
"the factory method is for multiple concrete classes that have the exact same implementation as the abstract base class [interface] and do not add their own properties."
No, speaking more practical, than theorical, the factory method can provide you with objects of concrete classes, in which the concrete classes, must have some common methods and interfaces, but, also some additional specific attributes.
Sometimes I use a method that creates the same class object every time I called, and I need to call it several times, and sometimes I use a method that create several different class objects, and that maybe be confusing, maybe another question.
And, your further comment about a switch sentence, with many options, when using the factory pattern, you usually provide an identifier for the concrete class / concrete object. This can be a string, an integer, an special type id, or an enumerated type.
You could use an integer / enum ID instead, and use a collection to lookup for the concrete class.
You can still leverage a factory. The point of a factory IMO is to put all the heavy lifting of constructing your various TVs in one place. To say categorically "a factory is for multiple concrete classes that have the exact same implementation as the abstract base class" is forgetting about polymorphism.
There is no law that says you cannot use a factory pattern because the sub classes declare unique properties and methods. But the more you can make use of polymorphism, the more a factory pattern makes sense. Also as a general guideline, IMHO, the more complexity that must go into constructing from the base the better off you are in the long run using a factory because you are "encapsulating change" - that is, constructing concrete classes is likely to change due to differing requirements and inherent construction complexity (a design analysis decision, to be sure) . And that change is in a single class - the factory.
Try this: Define everything in the abstract class and then for a given TV subclass either write concrete-specific code, and for those that don't apply write some standard "I don't do that" code.
Think about all the things your TVs do in generic terms: turn on, turn off, etc. Write a virtual method shell in the base class for all the generic things a TV does - this is a simple example of the template method pattern by the way. Then override these in the concrete classes as appropriate.
There are other things you can do in the base class to make it more fundgeable (that's a technical term meaning "reference subclasses as the base class, but do sub-classy things").
Define delegate methods (very powerful yet under-utilized)
use params[] for dynamic method parameter lists
Make Property delegates
Static methods
Declare Properties and methods "abstract" - forces sub-class implementation, vis-a-vis "virtual"
Hide inherited stuff in the sub class (generally using "new" keyword to communicate that it's on purpose)
If construction parameters are numerous or complex, create a class specifically designed to pass configuration to the factory's build method.
public class TVFactory {
public TV BuildTV(Brands thisKind) {
TV newSet;
switch (thisKind) {
case Brands.Samsung :
Samsung aSamsungTV = new Samsung();
aSamsungTV.BacklightIntensity = double.MinVal;
aSamsungTV.AutoShutdownTime = 45; //oops! I made a magic number. My bad
aSamsungTV.SetAutoShutDownTime = new delegate (newSet.SetASDT);
newSet = aSamsungTV;
break;
. . .
} // switch
}
//more build methods for setting specific parameters
public TV BuildTV (Brands thisKind, string Size) { ... }
// maybe you can pass in a set of properties to exactly control the construction.
// returning a concrete class reference violates the spirit of object oriented programming
public Sony BuildSonyTV (...) {}
public TV BuildTV (Brands thisKind, Dictionary buildParameters) { ... }
}
public class TV {
public string Size { get; set; }
public string ScreenType { get; set; }
public double BackLightIntensity { get; set; }
public int AutoShutdownTime { get; set; }
//define delegates to get/set properties
public delegate int GetAutoShutDownTime ();
public delegate void SetAutoShutDownTime (object obj);
public virtual TurnOn ();
public virtural TurnOff();
// this method implemented by more than one concrete class, so I use that
// as an excuse to declare it in my base.
public virtual SomeSonyPhillipsOnlything () { throw new NotImplementedException("I don't do SonyPhillips stuff"); }
}
public class Samsung : TV {
public Samsung() {
// set the properties, delegates, etc. in the factory
// that way if we ever get new properties we don't open umpteen TV concrete classes
// to add it. We're only altering the TVFactory.
// This demonstrates how a factory isolates code changes for object construction.
}
public override void TurnOn() { // do stuff }
public override void TurnOn() { // do stuff }
public void SamsungUniqueThing () { // do samsung unique stuff }
internal void SetASDT (int i) {
AutoShutDownTime = i;
}
}
// I like enumerations.
// No worries about string gotchas
// we get intellense in Visual Studio
// has a documentation-y quality
enum Brands {
Sony
,Samsung
,Phillips
}

Private 'set' in C# - having trouble wrapping my brain around it

I've seen a lot of example code written using something like (please forgive how horribly canned this is):
public class Test
{
public object Thingy { get; private set; }
}
Unfortunately, these kinds of examples never really explain why 'set' is set as private. So, I'm just wondering if there's a good, common example that will illustrate to me why something like this would be used.
I sort of see it - the property can be run to process some extra logic in addition to setting that field. I'm just confused on how it would be invoked, and why this approach would be used rather than a generic setter method.
This would be if you have a property that you don't want anyone to set but your class. This can be handy with database id's. The internal class can set it but you wouldn't want anyone else changing it. So you can give them read access but not write.
EDIT: One more point on this is that using what you showed there is helpful for automatic properties. Unfortunately with automatic properties you are unable to only specify get so to avoid exposing a setter publicly it is just made private.
EDIT: Just thought I would throw in an example. Automatic properties are great for clean, terse code. But like you showed there is a limitation in that you have to have get and set. So before it was like this for a property like you showed:
public class Test
{
private object thingy;
public object Thingy
{
get { return thingy; }
}
}
Now we can get rid of that unneeded private declaration but it requires both. So make private to get around that.
I know this was overkill on the explanation but different things kept popping in my head.
As a simple example; it is a cheap way of making an "immutable enough" object (for use in threading, state, etc). But also anywhere where the client simply shouldn't need to assign it, or can't be trusted to assign it (correctly).
Another example might be a list:
public List<Foo> Items {get;private set;}
since we might call obj.Items.Add() etc, but we would rarely assign obj.Items = .... However, this example is marred by needing explicit initialization in the constructor, and XmlSerializer hates it - to be honest for lists I mainly use:
private readonly List<Foo> items = new List<Foo>();
public List<Foo> Items {get { return items;}}
which solves both of these.
As another example, contrasting:
private readonly int foo;
public int Foo {get{return foo;}}
vs
private readonly int foo;
public int Foo {get{return foo;} private set {foo=value;}}
this pattern may be useful in serialization, for example with DataContractSerializer (with the addition of some attributes), since many serializers will still look for private accessors. This avoids us having to decorate our internal state (foo), but gives the veneer of privacy to the set.
Ultimately anything can be bypasses and assigned via reflection, so private set is only intended to avoid accidental damage to data.
The private makes it into a readonly property. A common example is if you have multiple classes passing around a single object, you don't want another class to be able to modify the instance.
Basically, it is a readonly property. If it was written in full (not as an auto property) you would simply leave out the setter.
Two examples that are largely the same:
class Foo1
{
public int Id { get; private set; }
public Foo1()
{
Id = lastId ++;
}
}
class Foo2
{
private int _id;
public int Id { get { return _id; } }
public Foo2()
{
_id = lastId ++;
}
}
I've seen this used with the design:
public class whatever
{
public string WhateverId { get; private set; }
public static whatever Create(string whateverId)
{
return new whatever() { WhateverId = whateverId };
}
}
So you create whatever class, but after it's created the id can't be changed because it might break things that are connected to it.
the private set just gives the simple initializer syntax, I kind of like it for some scenarios.
Also can be used if it's changeable, but you need to manage it when changes are made
public void SetWhateverId(string whateverId)
{
DisconnectAllCurrentWhateverIdReferences();
WhateverId = whateverId;
ReconnectAllPreviousWhateverIdReferences();
}
This syntax allows you to provide a public-facing property that appears read-only to consumers of your API but internally can be changing. By auto-implementing in this way, you avoid having to write boilerplate code such as a distinct setter or a backing field for the value, and you leave room in your design to add a bespoke set algorithm if it is deemed necessary at some point in the future without having to decide right away.
private set is very handy for simple immutable value types.
struct Point
{
public int X { get; private set; }
public int Y { get; private set; }
public Point(int x, int y)
{
this = default(Point);
X = x;
Y = y;
}
}
This is just laziness that comes about from auto-properties. Before auto properties were around, people would implement the getter and omit the setter for properties which are meant to be read-only.
public class Test
{
private /*readonly*/ Type _thingy;
public Type Thingy { get { return _thingy; } }
}
Hopefully, C# 5 will allow you to create auto-properties with a getter only - because that's what everyone wants. (They should make readonly setters in auto-props too, I need that badly)
To answer the question of a common scenario where this might be used...
In an MVP pattern, if your Model exposes some properties for your Presenter I would write
public string Bazinga { get; private set; }
Now, the Model can change this value but other classes that use it cannot.

Categories