It is useful when you start off with a class in which some of the data members are directly exposed, but then you realise (maybe through changing requirements) that some validation is needed. Then you can just define the setter and getter methods but don't need to change the code which accesses the data members.
Originally Posted by 0026sd
Ok, here's a new question. Is this one way of accessing properties from another class without actually creating a new instance of that class?
No, it is purely a different syntax to do what you would previously have done using GetX(), SetX() methods.
It is useful when you start off with a class in which some of the data members are directly exposed, but then you realise (maybe through changing requirements) that some validation is needed. Then you can just define the setter and getter methods but don't need to change the code which accesses the data members.
No, it is purely a different syntax to do what you would previously have done using GetX(), SetX() methods.
Is this one way of accessing properties from another class without actually creating a new instance of that class?
As Peter pointed out, not really, but understand that you can define a property as static. There are also the concept of auto-properties.
Let's look at a contrived example of a class that holds a static Timeout value.
Code:
class static Utility
{
public static Utility( )
{
Timeout = 5000; // uses the private setter for the Timeout property
}
public static int Timeout { get; private set; } //auto property with private setter
}
To use the class, we invoke it using the static syntax:
Code:
int timeout = Utility.Timeout; // timeout is set to 5000 using the public Timeout getter
Of course, in the example above you would probably use a const int value for Timeout rather than a static int.
Bookmarks