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

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.

Related

What is the point of making separate public functions for getting/setting a private value?

Let me just preface this by saying that I know this is probably a newbie quesion, I tried searching for it and I can't find a proper anwser for it (probbably asking it wrong).
So usually when I want to use another value outisde of its class, I just make it public and access it lik.
Yet often I see other code use private values in their class and then make separate functions for getting and setting the value like so:
private bool fooBar;
public void SetFooBar(bool boolean)
{
fooBar = boolean;
}
public bool GetFooBar()
{
return fooBar;
}
Excuse my ignorance but what exactly is the point of it? They both do essentially the same thing (by my newbie logic atleast). I know that private variables are useful in that it ensures you can't break the functionality of a program by modifying them elsewhere in the code, but you're modifying them elsewhere in the code anyway, so what gives? Why do I see people do this?
Because directly modifying the state of an object is a no-no in OOP
Because you can't put fields into an interface (and once you get far enough, you usually end up accessing most other objects through interfaces)
Because it allows additional logic (like raising events) when another object wants to interact with the field
Because certain things (like WPF bindings) only work with properties, not fields
Because you may want to change how the value is retrieved/stored (not just in-memory) later
(Note that in C# you usually do this as a property, not methods, like public bool Foo {get; set;})
This allows you to change the way the value is stored regardless of how external users access it.
Using Getter and Setter functions, you could request the data from a local cache or pull it from a database.
C# supports Getter Setter functionality implementations using a property style accessor.
private bool _fooBar
public bool FooBar
{
get { return _fooBar; }
set { _fooBar = value; }
}
As BradleyDotNET mentioned in the comments, you can write these in a way that resembles lambdas starting with C# 7.0
private bool _fooBar
public bool FooBar
{
get => _fooBar;
set => _fooBar = value;
}
As BradleyDotNET mentioned you can write this exact implementation as
public bool FooBar { get; set; }
Which will act the same way.
You can also expand upon this by making the value only public to get, but only settable in the class.
public bool FooBar { get; protected set; }

I'm not understanding the usage of C# get; set; seems to be different from Java

I know there are a few questions on stack overflow on this already but I haven't found any that answer my specific question. I came from a java development background and never bothered using the get; set; methods from C# until now.
I have the following code
class Test
{
public int test { get; set; }
}
In my main function I can declare a new Test and use t.Test = 5 and that works fine; however, when I switch the public to private I cannot access my get; and set; methods anymore... BUT when I use (Similar method to Java)
class Test
{
private int test;
public int getTest()
{
return this.test;
}
public void setTest(int test)
{
this.test = test;
}
}
I'm confused on the design philosophy. In C# should I no longer be using private variables (Only make it private if it's used internally in the class) and make them all public and use private get; private set; to control accessibility?
When you write this (I'm using different class and property names for clarity):
public class Test
{
public string Name { get; set; }
}
that's asking the compiler to create a private field with a public property. It's equivalent to:
public class Test
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
(Except the field name is autogenerated and not directly representable in C#.)
That's basically equivalent to what you'd write in Java as:
// Java
public class Test {
private String name;
public String getName() {
return name;
}
public String setName(String name) {
this.name = name;
}
}
... but clearly the C# is a lot more compact.
Basically, C#'s properties make for more readable code than having getter and setter methods as normal methods - but that's all they are, really. They're just used differently in code. The automatically implemented properties (as per the first snippet) make "trivial" properties simpler to express. In C# 6, you can write read-only automatically implemented properties too, which can be assigned to from the constructor but only the constructor.
Importantly though, you're still only making the properties part of the public API - not the fields. So if you later want to add some more logic (e.g. to have two properties derived from the same field, or something like that) you can do so without affecting either source or binary compatibility.
and make them all public and use
private get; private set; to control accessibility?
No, not really. Let's have a look at this scenario:
private int _a;
public int A
{
get { return _a; }
private set { _a = value; }
}
So this field _a is encapsulated and cannot be accesed from anywhere except the same class. But A is a public property and it is inside the class so it can access _a field and work with it however its set accessor is private, so it cannot be accessed from outside of the class...
But to do something like this usually makes little sense :
private int MyProperty { get; set; }
Ok, we created auto-implemented property to access private fields that it work with. But this property is private (used only inside the same class) and because it's auto-implemented it cannot contain any logic inside.
But if change it to :
public int MyProperty { get; private set; }
It's more useful and the main difference from first example is that it creates backing field automatically. Though it still impossible to add some logic but it encapsulates setter method and it's a way of creating read-only properties (at least read-only outside of class).
The other answer is true but I think it misses something important.
When you have:
class Test
{
public int test { get; set; }
}
There is an unseen, private variable in your class called something like _test. This is not accessible outside of the class and is accessed with get and set with set. For the most part, you won't change those methods, but the option is there for you in the future if you want to.
What you are using here are Auto-Implemented Properties.
In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
In other words, the two code blocks you posted are functionally the same.
The part that might not be obvious is that you also can declare either the getter or setter private, not necessarily the whole property, i.e.
public int test { get; private set; }
which would make it possible to get the value, but impossible to set the value from outside the class.
However, for small classes or structs that just encapsulate a set of values (data) and have little or no behaviors, you should either make the objects immutable by declaring the set accessor as private (immutable to consumers) or by declaring only a get accessor (immutable everywhere except the constructor). For more information, see How to: Implement a Lightweight Class with Auto-Implemented Properties (C# Programming Guide).
Yes, you use private variables only when you need to scope things internally to your class. They're obviously not visible from the outside.
The main reason for using Properties as they are known is when you want to add logic to your gets or sets. Say you want to validate a value before assignment, or you may want to delay load values and cache them in a get etc.
Here is a typical example when you'd want to use a property, over a simple value field:
private float latitude;
public float Latitude {
get { return this.latitude; }
set {
if(value < -90 || value > 90)
{
throw new ArgumentOutOfRangeException("Invalid Latitude");
}
this.latitude = value;
}
}
Now you could quite easily make the property private too, but you'd still be able to embed logic in there, obviously just not access it from outside. A singleton pattern is an example that springs off the top of my head.
You can also make the setting private for a variable. This allows you more flexibility to prevent people updating something they shouldn't, yet still give them access to the variable if need be.
private float latitude;
public float Latitude {
get;
private set;
}

c# getters setters style

I'm working on some code where there is lots of code like this:
private int x;
public void SetX(int new_x)
{
this.SetXValue(new_x);
}
private void SetXValue(int new_x)
{
this.x = new_x;
}
and similarly with properties:
private int x;
public int X
{
get { return this.GetX(); }
}
private int GetX()
{
return this.x;
}
What i don't get is why the need for the private methods which do the actual work, i.e. why not just have methods like this instead:
public void SetX(int new_x)
{
this.x = new_x;
}
public int X
{
get { return this.x; }
}
is it just the other persons personal choice or is there some good reason for using the first way?
(i typed above code manually so sorry if any mistakes but you should hopefully see what i'm trying to say)
Cheers
A
There's no reason for code like that as far as I can see. If you're not doing anything with the new values (like processing/checking before storing) and you're writing C# 3.0 you can actually just shorthand it it to this:
public int MyProperty { get; set; }
The compiler creates the backing store for you and you can just reference:
this.MyProperty
...inside your class. You can also create get-only properties like:
public int MyProperty { get; private set; }
All of which I think is pretty neat!
Why don't you use the Getters and Setters directly to implement your logic? I don't understand the need for additional methods unless you have extra parameters that influence the setter's behavior:
private int myVar;
public int MyProperty
{
get
{
return myVar;
}
set
{
myVar = value;
}
}
public void SetMyPropertySpecial(int a, string reason)
{
Console.WriteLine("MyProperty was changed because of " + reason);
this.myVar = a;
}
Update:
Indeed, this person seems to like having more lines of code, but the structure is utterly useless. Stick to .NET standards using Getters and Setters (see MSDN)
No, there is no reason for doing this, it looks liks someone was paid by lines of code.
So, yes, you're right, this is just the other persons personal choice, and it's not a very good one.
A general rule of thumb is to use properties for simple get/set operations and get/set methods when there is a relevant part of logic needed to get/set a value (e.g. validation during set or database access during get).
So if the actual code is really as simple as in your example just use properties and do the work in their getters/setters.
If the actual code is more complex replace the properties (at least the setters) by methods as in your third example.
One possible reason would be that the properties can have login that should be executed only when the property is set externally and calls from inside the class do not execute the whole logic but only the logic in the private method. Of course it makes no sense to make these methods in advance because introducing them later will not change the contract of the class. Chances are that whoever wrote this code was new to C# and did not understand what properties do.
I think it must be an old Java developper that did this.
The .Net way is
private int _foo;
public int Foo
{
get
{
return _foo;
}
set
{
_foo = value;
dostuff();
}
}
That's very bizarre, there's no justifiable reason for doing that. Please refactor that code. There's also no need for a SetX method as setter can be included in properties. e.g.:
public int X {get; set;}
i may be missing something here, but this looks a bit mad to me!
You can achieve the same by either using automatic properties or properties with backing fields. here's a good description of both: http://weblogs.asp.net/dwahlin/archive/2007/12/04/c-3-0-features-automatic-properties.aspx
Yes, that is fine only if the SetValue is private or protected and is doing more than just setting a value.
I am working on a project where we do a lot of those things. That is because we are doing more than just setting a value (value checks, state checks etc.)
Having a public setter and a public SetValue does not make sense at all and will confuse your consumers as to what setter to use.
Here is another scenario where we use this kind of design:
public abstract class A{
protected virtual void SetValue(object value);
public object SomeObject{
set{SetValue(value);}
}
}
In this case, we want class A to delegate setting/checking that value to whatever class inheriting from it.

How can one type access a private setter of another type's property?

All I need is a way to make a property of one class only 'settable' from one other class (a sort of manager class).
Is this even possible in c#?
My colleague 'reliably' informs me that I have a design flaw, but I feel I should at least ask the community before I concede defeat!
No, it's not really possible to do this in any clean way in C#. You probably have a design flaw ;-)
You can use the internal modifier, which lets all types in the same assembly access the data (or nominated assemblies if using [InternalsVisibleTo] - but no: there is no friend equivalent in C#.
For example:
public string Foo {get; internal set;}
You have a design flaw. Also, don't be paranoid about data hiding. Here's 3.5's way to do it:
class Program
{
static void Main(string[] args)
{
Managed m = new Managed();
Console.WriteLine(m.PrivateSetter);
m.Mgr.SetProperty("lol");
Console.WriteLine(m.PrivateSetter);
Console.Read();
}
}
public class Managed
{
private Manager _mgr;
public Manager Mgr
{
get { return _mgr ?? (_mgr = new Manager(s => PrivateSetter = s)); }
}
public string PrivateSetter { get; private set; }
public Managed()
{
PrivateSetter = "Unset";
}
}
public class Manager
{
private Action<string> _setPrivateProperty;
public Manager(Action<string> setter)
{
_setPrivateProperty = setter;
}
public void SetProperty(string value)
{
_setPrivateProperty(value);
}
}
Here's how we'd do it in pre-lambda days:
public class Managed
{
private Manager _mgr;
public Manager Mgr
{
get { return _mgr ?? (_mgr = new Manager(this)); }
}
public string PrivateSetter { get; private set; }
public Managed()
{
PrivateSetter = "Unset";
}
public class Manager
{
public void SetProperty(string value)
{
m.PrivateSetter = value;
}
private Managed m;
public Manager(Managed man)
{
m = man;
}
}
}
The best way to do it would be:
/// <summary>
/// Gets or sets foo
/// <b>Setter should only be invoked by SomeClass</b>
/// </summary>
public Object Foo
{
get { return foo; }
set { foo = value; }
}
When you have some complex access or inheritance restriction, and enforcing it demands too much complexity in the code, sometimes the best way to do it is just properly commenting it.
Note however that you cannot rely on this if this restriction has some security implications, as you are depending on the goodwill of the developer that will use this code.
You cannot do that on that way, but you can access a property's setter method from a derived class, so you can use inheritance for the purpose. All you have to do is to place protected access modifier. If you try to do so, your colleague is right :). You can try doing it like this:
public string Name
{
get{ return _name; }
protected set { _name = value; }
}
keep in mind that the set method of the property is only accessible from the derived class.
Or you could have these two classes in an assembly alone and have the setter as internal. I would vote up for the design flaw though, unless the previous answer by milot (inheriting and protected) makes sense.
You could do:
public void setMyProperty(int value, Object caller)
{
if(caller is MyManagerClass)
{
MyProperty = value;
}
}
This would mean that you could use a 'this' pointer from the calling class. I would question the logic of what you're attempting to achieve, but without knowing the scenario I can't advise any futher. What I will say is this: if it is possible to refactor your code to make it clearer, then it is often worthwhile doing so.
But this is pretty messy and certinly NOT fool-proof ... you have been warned!
Alternativly...
You could pass a delegate from the Class with the Property (Class A) to the Manager Class (Class B). The delegate can refer to a private function within A to allow B to call that delegate as any normal function. This precludes that A knows about B and potentially that A is created before B. Again... messy and not fool-proof!
You can achieve to this by making a Public property in your "settable class" that will inherit from the real class that will have a protected property... this way only the inherit class can SET and not class that doesn't inherit. But the drawback is that you will require to have an inherit class...
Reflection, though I would agree that having to do this just to get around an access modifier is probably an indication of a bad design.
public class Widget
{
private int count;
public int Count
{
get { return this.count; }
private set { this.count = value; }
}
}
public static class WidgetManager
{
public static void CatastrophicErrorResetWidgetCount( Widget widget )
{
Type type = widget.GetType();
PropertyInfo info = type.GetProperty("Count",BindingFlags.Instance|BindingFlags.NonPublic);
info.SetValue(widget,0,null);
}
}
The reason this is a design flaw is because it seems muddled between the scope of the two objects.
The properties of a class should be accessible in the context of that class, at least internally.
It sounds like the settable property on your item class is really a property of the manager class.
You could do something similar to what you want by closely coupling the two classes:
public class MyItem {
internal MyItemManager manager { get;set; }
public string Property1 {
get { return manager.GetPropertyForItem( this ); }
}
}
Unfortunately this isn't great design either.
What your looking for is what C++ calls a Friend class but neither c# or vb has this functionality. There is a lot of debate as to the merit of such functionality since it almost encourages very strong coupling between classes. The only way you could implement this in c# would be with reflection.
If your goal is to have a class Foo let some property (e.g. Bar, of type Biz) to be changed by some other object, without exposing it publicly, a simple way to do that is to have an instance of Foo which is supposed to be changeable by some other object to pass that other object an Action<Biz> which points to a private method that changes Bar to the passed-in value. The other object may use that delegate to change the Bar value of the object that supplied it.
If one wishes to have give all instances of some type Woozle the ability to set the Bar value of any instance of Foo, rather than exposing such abilities on a per-instance basis, one may require that Woozle have a public static method Woozle.InstallFooBarSetter which takes a parameter of type Action<Foo, Biz> and one of type Object. Foo should then have a static method WoozleRequestBarSetter which takes an Object, and passes it to Woozle.InstallFooBarSetter along with an Action<Foo,Biz>. The class initializer for Woozle should generate a new Object, and pass it to Foo.RequestBarSetter; that will pass the object to Woozle.InstallFooBarSetter along with a delegate. Woozle can then confirm that the passed-in object is the one that it generated, and--if so--install the appropriate delegate. Doing things this way will ensure that nobody but Woozle can get the delegate (since the delegate is only passed to Woozle.InstallFooBarSetter), and Woozle can be sure its delegate comes from Foo (since nobody else would have access to the object that Woozle created, and Woozle.InstallFooBarSetter won't do anything without it).
if it is a design flaw depends on what you want to do. You could use the StackTrace class from System.Diagnostics to get the Type of the class setting your property and then compare to the type you want to allow setting yor property..but maybe there are better ways for performing something like this (e.g. boxing)

How can I access the backing variable of an auto-implemented property?

In the past we declared properties like this:
public class MyClass
{
private int _age;
public int Age
{
get{ return _age; }
set{ _age = value; }
}
}
Now we can do:
public class MyClass
{
public int Age {get; set;}
}
My question is, how can I access the private variable that is created automatically using this notation?
I would rather access the private variable and not the public accessor 'Age'. Is there a default notation to access the private variable, or it is just not possible?
The aim of the new automatic properties is to reduce the amount of boilerplate code you need to write when you just have a simple property that doesn't need any special logic in the get or the set.
If you want to access the private member that these properties use, that's usually for a few reasons:
You need to more than just a simple get/set - in this case, you should just avoid using automatic properties for this member.
You want to avoid the performance hit of going through the get or set and just use the member directly - in this case, I'd be surprised if there really was a performance hit. The simple get/set members are very very easy to inline, and in my (admittedly limited) testing I haven't found a difference between using the automatic properties and accessing the member directly.
You only want to have public read access (i.e. just a 'get') and the class write to the member directly - in this case, you can use a private set in your automatic property. i.e.
public class MyClass
{
public int Age {get; private set;}
}
This usually covers most the reasons for wanting to directly get to the backing field used by the automatic properties.
Your usage of automatic properties implies that you do not need any getting/setting logic for the property thus a private backing variable is unneccessary.
Don't use automatic properties if you have any complex logic in your class. Just go private int _age and normal getters/setters as you normally would.
IMO, automatic properties are more suited for quickly implementing throwaway objects or temporary data capsules like:
public class TempMessage {
public int FromID { get; set; }
public int ToID { get; set; }
public string Message { get; set; }
}
Where you don't need much logic.
This syntax is commonly called "syntax sugar", which means that the compiler takes that syntax and translates it into something else. In your example, the compiler would generate code that looks something like this:
[CompilerGenerated]
private int <Age>k_BackingField;
public int Age
{
[CompilerGenerated]
get
{
return this.<Age>k_BackingField;
}
[CompilerGenerated]
set
{
this.<Age>k_BackingField = value;
}
Even knowing all of that, you could probably access the backing field directly but that sort of defeats the purpose of using automatic properties. I say probably here because you then depend on an implementation detail that could change at any point in a future release of the C# compiler.
Behind the scenes what happens is the injection of a private member variable, prefixed with <>k__AutomaticallyGeneratedPropertyField#
From C# 3.0 Automatic Properties explained
Although it may be possible to use that private member directly, it's very hacky and unnecessary.
You shouldn't, and it's very unlikely you need to. If you need to access the property, just use the public property (e.g. this.Age). There's nothing special about the private field backing the public property, using it in preference to the property is just superstition.
You can't, it's a language feature as opposed to a IDE feature. To be honest i'd prefer then IDE to add the private variable in for you. I agree that it is slightly weird for the class to internally have to use the public entry point to access its own variables. Hence I don't use this new feature that much myself.

Categories