Created
February 27, 2014 14:35
-
-
Save ThatRendle/9251262 to your computer and use it in GitHub Desktop.
Ultra-private field: force access of variable via property even within class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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