I saw some get set method to set values. Can anyone tell me the purpose of this?
public string HTTP_USER_NAME
{
get
{
return UserName;
}
set
{
UserName = value;
}
}
public string HTTP_USER_PASSWORD
{
get
{
return UserPwd;
}
set
{
UserPwd = value;
}
}
Actually why use these things. For global access, or is there some other reason for this type of thing?
They are just accessors and mutators. That's how properties are implemented in C#
In C# 3 you can use auto-implemented properties like this:
public int MyProperty { get; set; }
This code is automatically translated by the compiler to code similar to the one you posted, with this code is easier to declare properties and they are ideal if you don't want to implement custom logic inside the set
or get
methods, you can even use a different accessor for the set
method making the property immutable
public int MyProperty { get; private set; }
In the previous sample the MyProperty
will be read only outside the class where it was declared, the only way to mutate it is by exposing a method to do it or just through the constructor of the class. This is useful when you want to control and make explicit the state change of your entity
When you want to add some logic to the properties then you need to write the properties manually implementing the get
and set
methods just like you posted:
Example implementing custom logic
private int myProperty;
public int MyProperty
{
get
{
return this.myProperty;
}
set
{
if(this.myProperty <=5)
throw new ArgumentOutOfRangeException("bad user");
this.myProperty = value;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With