Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

If you wish to access MyConst from another class then you are no longer encapsulating it. Adding properties or method calls around this will not mean it is encapsulated. It's a constant. It cannot change. So either its publicly accessible or it's not. If another class needs access, make it internal or public.

Anything else is somewhere between denial and a code smell.

make a public property that returns MyConst?

public string MyPublicConst {get{ return MyConst;} private set; } - but why do you want to do this?

You can have it public (Duh!), you can use a property to encapsulate it if you are planning on changing it from a constant to something else, or you could have a method that return it to you.

class Encapsulation{ 
            private string a;

            public string AccessValue(){

                return a;
            }
         }

you can do that to any variable I think, for sure the simple ones.

This is a public method from the same class that returns the same value of the private string. In that way you can get the value from outside the class without declare it as public.

To reach it from another class you can just write:

class Player{ string b = Encapsulaion.AccessValue()}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top