Skip to content

Instantly share code, notes, and snippets.

@markrendle
Created February 27, 2014 14:35
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markrendle/9251262 to your computer and use it in GitHub Desktop.
Save markrendle/9251262 to your computer and use it in GitHub Desktop.
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