Skip to content

Instantly share code, notes, and snippets.

@markrendle
Created Feb 27, 2014
Embed
What would you like to do?
Ultra-private field: force access of variable via property even within class
OK, so technically within the class you can still access the variable by calling getMyProperty or setMyProperty instead of via the property, but you still encapsulate the functionality with the getting and setting.
void Main()
{
var myInstance = new MyClass("One");
Console.WriteLine(myInstance.MyProperty);
myInstance.MyProperty = "Two";
Console.WriteLine(myInstance.MyProperty);
}
// Define other methods and classes here (yay, LINQPad!)
class MyClass
{
private readonly Func<string> getMyProperty;
private readonly Action<string> setMyProperty;
public MyClass(string initialValue)
{
string myProperty = initialValue; // Will be closure for get and set functions
getMyProperty = () => {
DoSomething();
return myProperty;
};
setMyProperty = value => {
myProperty = value;
DoSomethingElse();
};
}
public string MyProperty
{
get { return getMyProperty(); }
set { setMyProperty(value); }
}
protected virtual void DoSomething()
{
Console.WriteLine("Done something.");
}
protected virtual void DoSomethingElse()
{
Console.WriteLine("Done something else.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment