Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More private than private? (C#)

Sometimes you have a private field that backs a property, you only ever want to set the field via the property setter so that additional processing can be done whenever the field changes. The problem is that it's still easy to accidentally bypass the property setter from within other methods of the same class and not notice that you've done so. Is there a way in C# to work around this or a general design principle to avoid it?

like image 376
Fxper Avatar asked Aug 19 '09 11:08

Fxper


3 Answers

IMHO, it is not used, because:

  • The class must trust itself
  • If your class gets as large that one part does not know the other, it should be divided.
  • If the logic behind the property is slightly more complex, consider to encapsulate it in an own type.
like image 170
Stefan Steinegger Avatar answered Oct 20 '22 22:10

Stefan Steinegger


I'd consider this a nasty hack and try to avoid it if possible, but...

You can mark the backing field as obsolete so that the compiler will generate a warning when you try to access it, and then suppress that warning for the property getter/setter.

The warning codes that you'd need to suppress are CS0612 for the plain Obsolete attribute and CS0618 if the attribute has a custom message.

[Obsolete("Please don't touch the backing field!")]
private int _backingField;

public int YourProperty
{
    #pragma warning disable 612, 618
    get { return _backingField; }
    set { _backingField = value; }
    #pragma warning restore 612, 618
}
like image 22
LukeH Avatar answered Oct 20 '22 22:10

LukeH


There's no inbuilt way to do what you want to do, but by the sounds of things you need another layer of abstraction between your class and that value.

Create a separate class and put the item in there, then your outer class contains the new class, and you can only access it through its properties.

like image 20
Binary Worrier Avatar answered Oct 20 '22 22:10

Binary Worrier