Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force get/set access of private variables for private properties

Tags:

c#

If I have a private variable that I want to have some internal validation on, and I want to keep that validation in one place, I put it behind a getter/setter and only access it thorugh that getter/setter. That's useful when dealing with public properties, because the other code cannot access the private variable, but when I'm dealing with object inside the class itself, is there any way to enforce the getter/setter?

  private int _eyeOrientation;

  private int eyeOrientation
  {
     get
     {
        return _eyeOrientation;
     }
     set
     {
        if (value < 0)
        {
           _eyeOrientation = 0;
        }
        else
        {
           _eyeOrientation = value % 360;
        }
     }
  }

The issue here being that the other functions in the class may accidentally modify

_eyeOrientation = -1;

which would throw the program into a tizzy. Is there any way to get that to throw a compiler error?

like image 487
DevinB Avatar asked May 11 '09 23:05

DevinB


People also ask

Can private variables be accessed by methods?

They are private in that they can only be accessed by that class. This means they are accessible from static methods of that class (such as main ) and also from instance methods (such as showData ). One instance of the class can also access private members of another instance of the class.

What is get private set in C#?

The code for getters is executed when reading the value. Since it is a read operation on a field, a getter must always return the result. A public getter means that the property is readable by everyone. While the private getter implies that the property can only be read by class and hence is a write-only property.

Can we modify private variable in Java?

Yes. By using reflection, you can access your private field without giving reference methods.


1 Answers

Sounds like you need a angle type.

// Non mutable Angle class with a normalized, integer angle-value
public struct Angle
{
  public Angle(int value)
  {
    Value = value;
  } 

  private angle;
  public Value 
  { 
    get { return angle; } 
    private set { angle = Normalize(value); } 
  }

  public static int Normalize(int value)
  {
     if (value < 0) return 360 - (value % 360);
     return value % 360;
  }
}

public class SomeClass
{
  public Angle EyeOrientation { get; set; }
}

If you have a certain kind of value, like angles, money, weight or whatever, it is always a good praxis to make it a own type, even if the value itself is stored in a int, decimal etc. This type makes your interfaces clearer and typesafe. It is not the same if you expect an Angle or a integer value as argument of some method.

like image 138
Stefan Steinegger Avatar answered Oct 05 '22 05:10

Stefan Steinegger