简体   繁体   中英

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

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;
   }
}

It seems as though you understand the functionality of getters and setters, and others answered that question. "Normal" class variables (without getters and setters) are called "fields", and "properties" (which have the getters and setters) encapsulate fields.

The purpose of properties is to control outside access to fields. If you want a variable to be read-only to outside logic, you can omit the setters, like so:

private int dataID;

public int DataID {
    get { return dataID; }
}

You can also make the setter private and achieve the same read-only functionality.

If an object has a chance of being null (for whatever reason), you can guarantee an instance always exists like this:

private Object instance;

public Object Instance {
    get {
        if (instance == null)
            instance = new Object();
        return instance;
    }
}

Another use for properties is defining indexers.

//in class named DataSet

private List<int> members;

public int this[int index] {
    get { return members[index]; }
}

With that indexer defined, you can access an instance of DataSet like this:

int member = dataSet[3];

Check these links,.. they gives clear explanation.

http://www.dotnetperls.com/property

http://code.anjanesh.net/2008/02/property-getters-setters.html

if UserName and UserPwd are class variables, better to use like this

_userName 
_userPwd

Standard way to implement properties in C# . UserName and UserPwd are private member variables ( string type) of the class where these 2 methods are defined.

HTTP_USER_NAME and HTTP_USER_PASSWORD are the public properties of your class. UserName and UserPwd could be your private field. And you are allowing other people to set or get the values via these public properties. No direct accesss to private propeties. Also you can do some logic inside the get method of the property.Ex : you will have a public property called Age and in the get method of that, you may read the value of your private field called " dateOfBirth " and do some calculation ( CurrentYear-dateOfBirth) and return that as the Age.

Properties are just accessors over fields. They allow to do certain operations (if needed), and provide controlled access to fields.

If you want to know when to use Properties, and when to use Only fields, Check the link Properties vs Fields – Why Does it Matter? (Jonathan Aneja)

From Properties (C# Programming Guide)

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

In this example, the TimePeriod class stores a time period. Internally the class stores the time in seconds, but a property named Hours enables a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.

Example

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}


class Program
{
    static void Main()
    {
        TimePeriod t = new TimePeriod();

        // Assigning the Hours property causes the 'set' accessor to be called.
        t.Hours = 24;

        // Evaluating the Hours property causes the 'get' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);
    }
}
// Output: Time in hours: 24

Properties Overview

  • Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.

  • A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. For more information, see Restricting Accessor Accessibility (C# Programming Guide) .

  • The value keyword is used to define the value being assigned by the set accessor.

  • Properties that do not implement a set accessor are read only.

  • For simple properties that require no custom accessor code, consider the option of using auto-implemented properties. For more information, see Auto-Implemented Properties (C# Programming Guide) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM