Since C# doesn't provide a mechanism for friend functions and classes, internal keyword doesn't help if I don't distribute code in separate assemblies and I can't always use nested classes, I came up with:
public sealed class FriendlyClass
{
private readonly string SecretKey = "MySecretKey";
public string PublicData { get; set; }
private string privateData;
public FriendlyClass()
{
PublicData = "My public data";
privateData = "My Private Data";
}
public string GetPrivateData(string key = null)
{
if (key == SecretKey)
return privateData;
else throw new System.InvalidOperationException("You can't call this method directly.");
return null;
}
public void SetPrivateData(string newData, string key = null)
{
if (key == SecretKey)
privateData = newData;
else throw new System.InvalidOperationException("You can't call this method directly.");
}
}
FriendlyClass friend = new FriendlyClass();
public void FriendlyMethod(string data)
{
friend.SetPrivateData(data, "MySecretKey");
}
public void StrangerMethod(string data)
{
friend.SetPrivateData(data);
}
FriendlyMethod("Data is changed");
StrangerMethod("Data is not changed");
It's ugly and lots to write. My question is: can someone still abuse the public methods of FriendlyClass, crash the code or produce unexpected behaviour?