If I have a class
public class Person
{
private const string MyConst = "SomeValue";
[MyAttribute(MyConst)]
public string Name {get;set;}
}
and inside other class I would like to access MyConst
what would be the best way to do so, keeping all encapsulated? Is it correct Person class?
It all depends on the protection you need on MyConst. If no body should be able to read or write this property other than Person then you shouldn't expose it through either Get or Set methods. If everybody can read but cant write this, then you can expose it through a read only property. If only one class (e.g. ClassB) can read it then you can provide a function in Person that takes a ClassB object and passes the private Const to it:
public class ClassB
{
private string ConstValue {get; set;}
public void SetConstValue(string constValue)
{
ConstValue = constValue;
}
public void GetConstFromPerson(Person p)
{
p.GetConstValue(this);
}
}
public class Person
{
private const string MyConst = "A";
public void GetConstValue(ClassB obj)
{
//todo: contract validations
obj.SetConstValue(MyConst);
}
}
[Edit]
Another solution is to define the constant as Internal and only have Person and CLassB in the assembly