Looking for a short & simple example of getters/setters in C#

后端 未结 12 432
悲哀的现实
悲哀的现实 2020-12-07 12:35

I am having trouble understanding the concept of getters and setters in the C# language. In languages like Objective-C, they seem an integral part of the system, bu

相关标签:
12条回答
  • 2020-12-07 12:49

    C# introduces properties which do most of the heavy lifting for you...

    ie

    public string Name { get; set; }
    

    is a C# shortcut to writing...

    private string _name;
    
    public string getName { return _name; }
    public void setName(string value) { _name = value; }
    

    Basically getters and setters are just means of helping encapsulation. When you make a class you have several class variables that perhaps you want to expose to other classes to allow them to get a glimpse of some of the data you store. While just making the variables public to begin with may seem like an acceptable alternative, in the long run you will regret letting other classes manipulate your classes member variables directly. If you force them to do it through a setter, you can add logic to ensure no strange values ever occur, and you can always change that logic in the future without effecting things already manipulating this class.

    ie

    private string _name;
    
    public string getName { return _name; }
    public void setName(string value) 
    { 
        //Don't want things setting my Name to null
        if (value == null) 
        {
            throw new InvalidInputException(); 
        }
        _name = value; 
    }
    
    0 讨论(0)
  • 2020-12-07 12:54

    In C#, Properties represent your Getters and Setters.

    Here's an example:

    public class PropertyExample
    {
        private int myIntField = 0;
    
        public int MyInt
        {
            // This is your getter.
            // it uses the accessibility of the property (public)
            get
            {
                return myIntField;
            }
            // this is your setter
            // Note: you can specify different accessibility
            // for your getter and setter.
            protected set
            {
                // You can put logic into your getters and setters
                // since they actually map to functions behind the scenes
                DoSomeValidation(value)
                {
                    // The input of the setter is always called "value"
                    // and is of the same type as your property definition
                    myIntField = value;
                }
            }
        }
    }
    

    You would access this property just like a field. For example:

    PropertyExample example = new PropertyExample();
    example.MyInt = 4; // sets myIntField to 4
    Console.WriteLine( example.MyInt ); // prints 4
    

    A few other things to note:

    1. You don't have to specifiy both a getter and a setter, you can omit either one.
    2. Properties are just "syntactic sugar" for your traditional getter and setter. The compiler will actually build get_ and set_ functions behind the scenes (in the compiled IL) and map all references to your property to those functions.
    0 讨论(0)
  • 2020-12-07 12:55

    This would be a get/set in C# using the smallest amount of code possible. You get auto-implemented properties in C# 3.0+.

    public class Contact
    {
       public string Name { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-07 12:59

    Most languages do it this way, and you can do it in C# too.

        public void setRAM(int RAM)
        {
            this.RAM = RAM;
        }
        public int getRAM()
        {
            return this.RAM;
        }
    

    But C# also gives a more elegant solution to this :

        public class Computer
        {
            int ram;
            public int RAM 
            { 
                 get 
                 {
                      return ram;
                 }
                 set 
                 {
                      ram = value; // value is a reserved word and it is a variable that holds the input that is given to ram ( like in the example below )
                 }
            }
         }
    

    And later access it with.

        Computer comp = new Computer();
        comp.RAM = 1024;
        int var = comp.RAM;
    

    For newer versions of C# it's even better :

    public class Computer
    {
        public int RAM { get; set; }
    }
    

    and later :

    Computer comp = new Computer();
    comp.RAM = 1024;
    int var = comp.RAM;
    
    0 讨论(0)
  • 2020-12-07 13:00

    I think a bit of code will help illustrate what setters and getters are:

    public class Foo
    {
       private string bar;
    
       public string GetBar()
       {
           return bar;
       }
    
       public void SetBar(string value)
       {
           bar = value;
       }
    }
    

    In this example we have a private member of the class that is called bar. The GetBar and SetBar methods do exactly what they are named - one retrieves the bar member, and the other sets its value.

    In c# 1.1 + you have properties. The basic functionality is also the same:

    public class Foo
    {
        private string bar;
    
        public string Bar
        {
            get { return bar; }
            set { bar = value; }
        }
    }
    

    The private member bar is not accessible outside the class. However the public "Bar" is, and it has two accessors - get, which just as the example above "GetBar()" returns the private member, and also a set - which corresponds to the SetBar(string value) method in the forementioned example.

    Starting with C# 3.0 and above the compiler became optimized to the point where such properties do not need to have the private member as their source. The compiler automatically generates a private member of that type and uses it as a source of a property.

    public class Foo
    {
       public string Bar { get; set; }
    }
    

    what the code shows is an automatic property that has a private member generated by the compiler. You don't see the private member but it is there. This also introduced a couple of other issues - mainly with access control. In C# 1.1, and 2.0 you could omit the get or set portion of a property:

    public class Foo
    {
        private string bar;
    
        public string Bar
        {
            get{ return bar; }
        }
    }
    

    Giving you the chance to restrict how other objects interact with the "Bar" property of the Foo class. Starting with C# 3.0 and above - if you chose to use automatic properties you would have to specify the access to the property as follows:

    public class Foo
    {
        public string Bar { get; private set; }
    }
    

    What that means is that only the class itself can set Bar to some value, however anyone could read the value in Bar.

    0 讨论(0)
  • 2020-12-07 13:00

    Getters and Setters in C# are something that simplifies the code.

    private string name = "spots";
    
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    

    And calling it (assume we have a person obj with a name property):

    Console.WriteLine(Person.Name); //prints "spots"
    Person.Name = "stops";
    Console.Writeline(Person.Name); //prints "stops"
    

    This simplifies your code. Where in Java you might have to have two methods, one to Get() and one to Set() the property, in C# it is all done in one spot. I usually do this at the start of my classes:

    public string foobar {get; set;}
    

    This creates a getter and setter for my foobar property. Calling it is the same way as shown before. Somethings to note are that you don't have to include both get and set. If you don't want the property being modified, don't include set!

    0 讨论(0)
提交回复
热议问题