Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the "get" and "set" properties in C#

Tags:

c#

asp.net

c#-4.0

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?

like image 787
TechGuy Avatar asked May 31 '12 04:05

TechGuy


1 Answers

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;
   }
}
like image 91
Jupaol Avatar answered Sep 27 '22 20:09

Jupaol