Force use members over fields - c#

Is there a way to force usage of properties instead of private backing fields?
For example:
//field
private string str;
// property
public string Str
{
get { return this.str; }
set { this.str = value; DoSomething(); }
}
Both members need to have read rights however only property should have write rights. How to achive that?
EDIT: I was talking about access rights inside the class. Not from outside.

I'm assuming the reason that you don't want to be able to write directly to str within the class is because DoSomething is tightly coupled to its value changing. So to deal with that, use separation of concerns principles: create an internal class and make it solely responsible for ensuring that coupling is maintained:
internal class StrDoSomethingCoupler
{
private readonly Action _doSomething;
private string str;
public StrDoSomethingCoupler(Action doSomething)
{
_doSomething = doSomething;
}
public string Str
{
get { return _str; }
set { _str = value; _doSomething(); }
}
}
public class SomeClass
{
private readonly StrDoSomethingCoupler _coupler =
new StrDoSomethingCoupler(DoSomething);
...
public string Str
{
get { return _couple.Str; }
set { _coupler.Str = value; }
}
}

Although not clear this is a good question. Let me rephrase it.
Class A
{
//field
private string _str;
// member
public string Str
{
get { return _str; }
set { _str = value; DoSomething(); }
}
public void SomeMethod()
{
_str = "Dont access like this";
Str= "Should access only like this";
}
}
Sadly the answer is No, you cannot restrict the access of _str within Class A. Its only a coding practice you should follow, no inbuilt language feature that supports it. Reference - Blocking access to private member variables? Force use of public properties?
There is a problem that I can see in the sample code. You are doing two things within the setter of Str.
i.e. set { _str = value; DoSomething(); } is a bad practice(Although some places its unavoidable, like NotifyPropertyChanged() in wpf).
So don't do that, better change that logic by separating DoSomething() from Str.set. Something like
Class A
{
//field
private string _str;
// member
public string Str
{
get { return _str; }
private set { _str = value; }
}
private void DoSomething()
{
..
..
}
public void UpdateStrAndDoSomething(string strValue)
{
Str = strValue;
DoSomething();
}
}

private string _str;
public string Str
{
get { return _str; }
private set { _str = value; DoSomething();
}

Related

Get and Set String Property returning Empty Property

I'm trying to get and set a property using the following code.
But the when trying to print the property using Console,it returns an empty string.Why is the property not getting set?
using System;
public class Program
{
public static void Main()
{
myclass x=new myclass();
x.myproperty="test";
Console.WriteLine(x.myproperty);
}
class myclass{
string sample;
public string myproperty
{
get { return sample;}
set {sample=myproperty;}
}
}
}
In setter you should use value to assign new value to underlying field
use this instead
public string myproperty
{
get { return sample; }
set { sample = value; }
}
or in C#7
public string myproperty
{
get => sample;
set => sample = value;
}
Edit
As #bradbury9 mentioned, you can also use auto-implemented properties, of course this is the case if you don't want any other logic in getter and setter than just getting and setting the field, if this is the case you can use below snippet
public string myproperty { get; set; }
value keyword is important for setting the value. In Visual Studio you can use propfull + double tab to avoid such common mistakes. It will create full property through shortcuts.
Here is the solution
public static void Main()
{
myclass x = new myclass();
x.myproperty = "test";
Console.WriteLine(x.myproperty);
}
class myclass
{
string sample;
public string myproperty
{
get { return sample; }
set { sample = value; }
}
}
If you just want to return null instead of empty string. This works even when you deserialize your Json:
class myclass
{
string sample;
[JsonProperty("my_property")]
public string My_property
{
get { return sample; }
set { sample = string.IsNullOrEmpty(value) ? null : value; }
}
}

Properties that update each other

So, in some C# code, I have something similar to the two properties:
private string _foo;
private string _bar;
public Foo
{
get;
set {
_foo = value;
Bar = _foo.Substring(3, 5);
}
}
public Bar
{
get;
set {
_bar = value;
Foo = "XXX" + _bar;
}
}
Question: Are C# properties subject to circular references/updates, like this example would seem to cause?
You can avoid the infinite loop by updating the hidden field directly, like this:
private string _foo;
private string _bar;
public string Foo
{
get { return _foo; }
set {
_foo = value;
_bar = _foo.Substring(3, 5);
}
}
public string Bar
{
get { return _bar; }
set {
_bar = value;
_foo = "XXX" + _bar;
}
}
This will bypass the other property's setter, which eliminates the loop.
But... this generally causes maintenance headaches later on. Personally, I'd try to find an alternative design.
Are C# properties subject to circular references/updates, like this example would seem to cause?
Yes. You have a nice, infinite loop here.
Properties in C# are simple methods (getter and setter). You call one method from other method and vice versa. Result is completely expected.
Would this surprise you?
public void set_Foo(string value)
{
set_Bar(value.Substring(3, 5));
}
public void set_Bar(string value)
{
set_Foo("XXX" + value);
}
Call set_Foo("XXX12345") and.. you'll see the name of this site
To avoid the infinite loop, here's an alternative to Philip Hanson's answer: run the setter lines only when the value actually changes. Be nice; this is my first post/answer
private string _foo;
private string _bar;
public Foo
{
get;
set {
if (_foo != value)
{
_foo = value;
Bar = _foo.Substring(3, 5);
}
}
}
public Bar
{
get;
set {
if (_bar != value)
{
_bar = value;
Foo = "XXX" + _bar;
}
}
}

C# getter and setter shorthand

If my understanding of the internal workings of this line is correct:
public int MyInt { get; set; }
Then it behind the scenes does this:
private int _MyInt { get; set; }
Public int MyInt {
get{return _MyInt;}
set{_MyInt = value;}
}
What I really need is:
private bool IsDirty { get; set; }
private int _MyInt { get; set; }
Public int MyInt {
get{return _MyInt;}
set{_MyInt = value; IsDirty = true;}
}
But I would like to write it something like:
private bool IsDirty { get; set; }
public int MyInt { get; set{this = value; IsDirty = true;} }
Which does not work. The thing is some of the objects I need to do the IsDirty on have dozens of properties and I'm hoping there is a way to use the auto getter/setter but still set IsDirty when the field is modified.
Is this possible or do I just have to resign myself to tripling the amount of code in my classes?
You'll need to handle this yourself:
private bool IsDirty { get; set; }
private int _myInt; // Doesn't need to be a property
Public int MyInt {
get{return _myInt;}
set{_myInt = value; IsDirty = true;}
}
There is no syntax available which adds custom logic to a setter while still using the automatic property mechanism. You'll need to write this with your own backing field.
This is a common issue - for example, when implementing INotifyPropertyChanged.
Create an IsDirty decorator (design pattern) to wrap some your properties requiring the isDirty flag functionality.
public class IsDirtyDecorator<T>
{
public bool IsDirty { get; private set; }
private T _myValue;
public T Value
{
get { return _myValue; }
set { _myValue = value; IsDirty = true; }
}
}
public class MyClass
{
private IsDirtyDecorator<int> MyInt = new IsDirtyDecorator<int>();
private IsDirtyDecorator<string> MyString = new IsDirtyDecorator<string>();
public MyClass()
{
MyInt.Value = 123;
MyString.Value = "Hello";
Console.WriteLine(MyInt.Value);
Console.WriteLine(MyInt.IsDirty);
Console.WriteLine(MyString.Value);
Console.WriteLine(MyString.IsDirty);
}
}
You can make it simple or complex. It depends on how much work you want to invest. You can use aspect oriented programming to add the aspect via an IL weaver into the IL code with e.g. PostSharp.
Or you can create a simple class that does handle the state for your property. It is so simple that the former approach only pays off if you have really many properties to handle this way.
using System;
class Dirty<T>
{
T _Value;
bool _IsDirty;
public T Value
{
get { return _Value; }
set
{
_IsDirty = true;
_Value = value;
}
}
public bool IsDirty
{
get { return _IsDirty; }
}
public Dirty(T initValue)
{
_Value = initValue;
}
}
class Program
{
static Dirty<int> _Integer;
static int Integer
{
get { return _Integer.Value; }
set { _Integer.Value = value; }
}
static void Main(string[] args)
{
_Integer = new Dirty<int>(10);
Console.WriteLine("Dirty: {0}, value: {1}", _Integer.IsDirty, Integer);
Integer = 15;
Console.WriteLine("Dirty: {0}, value: {1}", _Integer.IsDirty, Integer);
}
}
Another possibility is to use a proxy class which is generated at runtime which does add the aspect for you. With .NET 4 there is a class that does handle this aspect already for you. It is called ExpandObject which does notify you via an event when a property changes. The nice things is that ExpandoObject allows you to define at runtime any amount of properties and you get notifications about every change of a property. Databinding with WPF is very easy with this type.
dynamic _DynInteger = new ExpandoObject();
_DynInteger.Integer = 10;
((INotifyPropertyChanged)_DynInteger).PropertyChanged += (o, e) =>
{
Console.WriteLine("Property {0} changed", e.PropertyName);
};
Console.WriteLine("value: {0}", _DynInteger.Integer );
_DynInteger.Integer = 20;
Console.WriteLine("value: {0}", _DynInteger.Integer);
Yours,
Alois Kraus
I'm going to add on to Simon Hughes' answer. I propose the same thing, but add a way to allow the decorator class to update a global IsDirty flag automatically. You may find it to be less complex to do it the old-fashioned way, but it depends on how many properties you're exposing and how many classes will require the same functionality.
public class IsDirtyDecorator<T>
{
private T _myValue;
private Action<bool> _changedAction;
public IsDirtyDecorator<T>(Action<bool> changedAction = null)
{
_changedAction = changedAction;
}
public bool IsDirty { get; private set; }
public T Value
{
get { return _myValue; }
set
{
_myValue = value;
IsDirty = true;
if(_changedAction != null)
_changedAction(IsDirty);
}
}
}
Now you can have your decorator class automatically update some other IsDirty property in another class:
class MyObject
{
private IsDirtyDecorator<int> _myInt = new IsDirtyDecorator<int>(onValueChanged);
private IsDirtyDecorator<int> _myOtherInt = new IsDirtyDecorator<int>(onValueChanged);
public bool IsDirty { get; private set; }
public int MyInt
{
get { return _myInt.Value; }
set { _myInt.Value = value; }
}
public int MyOtherInt
{
get { return _myOtherInt.Value; }
set { _myOtherInt.Value = value; }
}
private void onValueChanged(bool dirty)
{
IsDirty = true;
}
}
I have created a custom Property<T> class to do common operations like that. I haven't used it thoroughly yet though, but it could be used in this scenario.
Code can be found here: http://pastebin.com/RWTWNNCU
You could use it as follows:
readonly Property<int> _myInt = new Property<int>();
public int MyInt
{
get { return _myInt.GetValue(); }
set { _myInt.SetValue( value, SetterCallbackOption.OnNewValue, SetDirty ); }
}
private void SetDirty( int oldValue, int newValue )
{
IsDirty = true;
}
The Property class handles only calling the passed delegate when a new value is passed thanks to the SetterCallbackOption parameter. This is default so it can be dropped.
UPDATE:
This won't work apparently when you need to support multiple types (besides int), because the delegate won't match then. You could ofcourse always adjust the code to suit your needs.

Stack overflow exception in C# setter

This works:
using System;
using ConstraintSet = System.Collections.Generic.Dictionary<System.String, double>;
namespace ConsoleApplication2
{
class test
{
public ConstraintSet a { get; set; }
public test()
{
a = new ConstraintSet();
}
static void Main(string[] args)
{
test abc = new test();
Console.WriteLine("done");
}
}
}
This does not:
using System;
using ConstraintSet = System.Collections.Generic.Dictionary<System.String, double>;
namespace ConsoleApplication2
{
class test
{
public ConstraintSet a { get { return a; } set { a = value; } }
public test()
{
a = new ConstraintSet();
}
static void Main(string[] args)
{
test abc = new test();
Console.WriteLine("done");
}
}
}
I get a stack overflow exception on a's setter in the second class and I do not know why. I cannot use the first form because it is not supported by the Unity game engine.
When you write a = value, you are calling the property setter again.
In order to use non-automatic properties, you need to create a separate private backing field, like this:
ConstraintSet a;
public ConstraintSet A { get { return a; } set { a = value; } }
You haven't declared a backing variable - you've just got a property whose getters and setters call themselves. It's not clear to me why the first form isn't supported by Unity - which means it's possible that the equivalent won't be supported either, but it's basically this:
private ConstraintSet aValue;
public ConstraintSet a { get { return aValue; } set { aValue = value; } }
I'd normally have a more conventional name, of course - which means you can get away without the "value` bit:
private ConstraintSet constraints;
public ConstraintSet Constraints
{
get { return constraints; }
set { constraints = value; }
}
To give a bit more detail as to why your current second form is throwing a StackOverflowException, you should always remember that properties are basically methods in disguise. Your broken code looks like this:
public ConstraintSet get_a()
{
return get_a();
}
public void set_a(ConstraintSet value)
{
set_a(value);
}
Hopefully it's obvious why that version is blowing the stack. The amended version just sets a variable instead of calling the property again, so it looks like this when expanded:
private ConstraintSet aValue;
public ConstraintSet get_a()
{
return aValue;
}
public void set_a(ConstraintSet value)
{
aValue = value;
}
You cannot use the same variable name inside the getter and setter. This will cause it to call itself and will eventually lead to a stack overflow. Too much recursion.
You'll need a backing variable:
private ConstraintSet _a;
public ConstraintSet a { get { return _a; } set { _a = value; } }
You need a private backing variable in your public property:
private ConstraintSet _a;
public ConstraintSet a { get { return _a; } set { _a = value; } }

Make this reflection method call typesafe

class CustomerMessage
{
private string name;
private Dictionary<MethodBase, object> changeTrackingMethods =
new Dictionary<MethodBase, object>();
public int Id { get; set; }
public string Name {
get { return this.name; }
set
{
this.name = value;
this.PropertyChanged("SetName", value);
}
}
private void PropertyChanged(string behaviorMethod, object value)
{
var method = typeof(Customer).GetMethod(behaviorMethod);
this.changeTrackingMethods.Add(method, value);
}
public void ApplyChanges(Customer c)
{
foreach (var changedProperty in this.changeTrackingMethods)
changedProperty.Key.Invoke(c, new object[] {
changedProperty.Value
});
}
}
As you can see I am tracking the changes on this incoming message, to run the changes on another object. The method to run is passed to PropertyChanged as a string. Does anyone have a tip how I can make this type safe?
Something like this?
class CustomerMessage
{
private string name;
private List<Action<Customer>> changeTrackingMethods =
new List<Action<Customer>>();
public int Id { get; set; }
public string Name {
get { return this.name; }
set
{
this.name = value;
this.changeTrackingMethods.Add(c => { c.SetName(value) });
}
}
public void ApplyChanges(Customer c)
{
foreach (var action in this.changeTrackingMethods)
{
action(c);
}
}
}
So you want to avoid passing the method name as a string? Why not get the MethodBase object in the setter?
public string Name {
get { return this.name; }
set
{
this.name = value;
this.PropertyChanged(typeof(Customer).GetMethod(behaviorMethod), value);
}
}
private void PropertyChanged(MethodBase method, object value)
{
this.changeTrackingMethods.Add(method, value);
}
Instead of storing the "operation that needs to be done" as a pair of method and an argument that should be passed to it using Reflection, you can store a delegate that should be executed. The simplest way to do this is to store a list of type List<Action<Customer>> - then in the ApplyChanges method, you can iterate over the list and run all the actions.
In case you're not using .NET 3.5 and C# 3.0 (which defines a generic delegate Action and supports lambda expressions), you can still write this in C# 2.0:
// you can define a delegate like this
delegate void UpdateCustomer(Customer c);
// and you could use anonymous methods
// (instead of more recent lambda expressions)
list.Add(delegate (Customer c) { c.SetName("test"); });
EDIT: It looks like I was slower with writing the code, but I'll keep this here as an explanation - the solution by 'dtb' does exactly what I described.

Categories