none
C# Get Set RRS feed

  • Question

  • I am struggling to find what I think should be a simple answer.  When it comes to properties of a Class and getting and setting the value of the property, which does which?  Grammar tells me, the Get actually Gets the value from the application, and then the Set sets that value of the property, which provides that value to the field(s) of the class.  For example:

    public class Product

    {

    private string code;

    public Product() {} //a default constructor

    public string Name

    {

        get 

        {

            return name;

         }

         set

         {

             name = value;

         }

    }

    It is my understanding, the actual C# code is providing the value, the 'name' of the product to the class.  But is the set receiving the value from the application and then in turn the get is getting that value from the set and then populating the field Name in the class?

    I know this is probably a very remedial question, but which is actually receiving the information from the application?  The Get or the Set?  Is the Set 'setting' the value based on what is provided from the application or is the Get 'getting' the value from the application and 'setting' that value in the class?

    BTW, I assume I have some terms and flow incorrect, so any corrections on terminology and flow are greatly appreciated.  I am having a hard time (no matter what I read) understanding how the data gets from the application to the class.

    Thanks!

    Friday, February 23, 2018 5:56 PM

All replies

  • Why do you not simply try your code, you learn much more from it and takes less time than writing this message. 

    Don't think that you can change with this message how it is used, it is simply as it is since the beginning of properties. 

    By the way, when you test it, than add a string name = "";


    Success
    Cor

    Friday, February 23, 2018 6:43 PM
  • Hello,

     We always welcome user to post when need some help. But, we also encourage users

    to do some research before posting. What you are asking about is without a doubt been

    asked in the past. You can always search current and past posts by topic, usually the

    question you have or some keywords. However, the following link is instructional;

     

     https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties

     

     The easy and simple way to explain the get and set accessor is the following;

     

     Get means you want the value of the object.

     Set means you want to change the value of the object.

     

      There really should not be any ambiguity or confusion about  the get/set purpose/function.

     

     Hope this helps :)

    Friday, February 23, 2018 7:11 PM
  • Trust me, I have looked, but in all the reading and Internet searches I have done, either they don't address the question, or I am too thick to understand the complicated answer.  It seems like a pretty straight forward questions, but I can't find the answer.

    Which gets the information from the application - get or set?  

    I will check the link you sent, because the more information I get the better, but my hope was to get an answer to what I thought was a simple question.  I have spent hours trying to find a straight forward answer, but it appears it does not exist.


    • Edited by tddyballgm Friday, February 23, 2018 7:31 PM
    Friday, February 23, 2018 7:29 PM
  • I appreciate your feedback, and I hate to ask for help.  I have done a good amount of research (both online and text books) and I have written and done code to perform the task, but that does not explain to me how it is working.  I can get it to work fine, but it's like driving a car - just because I know how to drive, doesn't mean I can tell you how the car works.  

    That is in no way meant to seem like a smart alack response, I truly don't.  I hate, HATE asking for help, but everything I have read and researched doesn't answer the my question:  Which gets the the data from the application - get or set?

    I am trying to shorten my learning curve.  I have spent hours trying to find the answer, but have been unable to.  But since I am stubborn, I will continue my search!  :)
    • Edited by tddyballgm Friday, February 23, 2018 7:32 PM
    Friday, February 23, 2018 7:31 PM
  • I would encourage you to read the docs on properties.

    Examine the following "after" reading the docs and read the comments, read info in the links. Try things out rather than think about it. Set break-points, step through code with the Visual Studio debugger and examine variables.

    namespace demo
    {
        /// <summary>
        /// Properties doc
        /// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
        /// </summary>
        public class Person
        {
            private string locationName;
            /// <summary>
            /// Overload the constructor for this class
            /// An expression body definition for a constructor typically consists of a single 
            /// assignment expression or a method call that handles the constructor's 
            /// arguments or initializes instance state.
            /// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members
            /// </summary>
            /// <param name="name"></param>
            public Person(string name) => locationName = name;
    
            /// <summary>
            /// Not needed in this case, only here to show that if there
            /// is work to do at the start place it here else delete this
            /// constructor
            /// </summary>
            public Person()
            {
    
            }
    
            /// <summary>
            /// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties
            /// </summary>
            public int Id { get; set; }
            public string FirstName { get; set; }
            /// <summary>
            /// By using a underscore at the beginning we would note this
            /// is a private var down in the code. If you where using ReSharper
            /// it recognizes this.
            /// </summary>
            private string _lastName;
            /// <summary>
            /// Conventional property with private
            /// variable
            /// </summary>
            public string LastName
            {
                get { return _lastName; }
                set { _lastName = value; }
            }
            /// <summary>
            /// Read-only property
            /// </summary>
            public string FullName
            {
                get { return $"{FirstName} {LastName}"; }
            }
            /// <summary>
            /// In C# 6 and later, you can initialize auto-implemented properties similarly to fields:
            /// </summary>
            public string Country { get; set; } = "USA";
        }
    }
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Friday, February 23, 2018 8:30 PM
    Moderator
  • Doing what you are doing is the old way that is tedious. You can use auto properties.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties

    Friday, February 23, 2018 10:07 PM

  • I am trying to shorten my learning curve.  I have spent hours trying to find the answer, but have been unable to.  But since I am stubborn, I will continue my search!  :)

    You ask this in the C# forum. C# is based on C type languages and is in fact a combination from C++, Java, VB and probably Delphi the first program language of Anders Hejlsberg the big man behind C#. 

    C#, VB (since version 7), C++ (managed) and Java share currently the same things. 

    It is based on instanced Classes from which the base is the Object Class. A Class has members, which are Methods, Properties and Constructors. 

    In WPF the properties become again important, but WPF is not an origanally Microsoft made product. Originally the property was a base principle how code was set to ILS and everything worked around it. Currently it has not much differences with a field. 

    Difficult is if you begin with looking to it from inside the (this) class. However you should seen it from outside the class.

    It was not by accident that I wrote in my first reply. 

    By the way, when you test it, than add a string name = ""; 

    Because "name" is the thing that has to be set or gotten (get) in your code. 


    Success
    Cor



    Friday, February 23, 2018 10:46 PM
  • It is my understanding, the actual C# code is providing the value, the 'name' of the product to the class.  But is the set receiving the value from the application and then in turn the get is getting that value from the set and then populating the field Name in the class?

    You don't understand one of the pillars of Object Oriented Programming in dealing with an object and the concepts of encapsulation

    http://csharp-station.com/Tutorial/CSharp/Lesson19

    Friday, February 23, 2018 11:16 PM
  • Hello tddyballgm,

    For some programming language, we don't call the field wrapper as property because the concept is confusion. In Java language we just call it as "Get Set method". For property you provided just equal below after compiled.

     
     public class ProductT
        {
            private string name;
            public string get_Name()
            {
                return name;
            }
            public void set_Name(string Na) {
                name = Na;
            }
        }

    The above code fully shows the essence of property, which just are "get" method, "set" method and the "value" of property just is parameter of set method. In this circumstance the "value" is "Na" parameter.

    you also could use ILDASM tool to decompile your product class.

    The above shows that Name property will be converted to get_Name method and set_Name method. Both have different method signature.

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Saturday, February 24, 2018 4:55 AM
    Moderator
  • Greetings tddyballgm.

    You are asking about a concept which is very simple once you have the hang of it, but can be difficult to explain in the first place. Here's my best shot at an explanation.

    The technically simplest way to expose a class's data is to add a variable and make it public, like so.

    public class MyClass
    {
       public string Name;
    }
    
    
    // Use like this.
    MyClass mc = new MyClass();
    mc.Name = "Joe Bloggs";
    Console.WriteLine(mc.Name);

    The problem is that, although this works, it violates the core principle of Object Oriented Programming that only an object should be able to access its own data. The outside world should be able to "ask" an object to change or provide its data, but not touch it directly (ask an Object Oriented Nazi why this is important).

    The first try at getting around this problem was for coders to provide "access functions" to private data. So the outside world can use the access functions to "request" access to the data, but can't touch the data directly. Like so.

    public class MyClass
    {
       private string Name;
    
       public string GetName(){return Name;}
       public void SetName(string name){Name = name;}
    }
    
    // Use like this.
    MyClass mc = new MyClass();
    mc.SetName("Joe Bloggs");
    Console.WriteLine(mc.GetName());

    This works, and satisfies OOP principles, but is rather awkward, and uses syntax that is not really designed for the purpose.

    The next step was to provide new syntax just for getting and setting.

    public class MyClass
    {
       private string name;
       // I personally prefer to compress these to one line.
       public string Name{get{return name;} set{name = value;}}
    }
    
    // Use like so.
    MyClass mc = new MyClass();
    mc.Name = "Joe Bloggs";
    Console.WriteLine(mc.Name);
    
    

    In this case, "name" (lowercase "n") is referred to as a "backing field". This was the standard syntax for a long time. It's a bit verbose, especially if you put each brace on a new line, as many people do (sometimes referred to as "line noise").

    The final stage (so far) was new syntax that allows the compiler to create the backing field for you.

    public class MyClass
    {
       public Name{get; set;}
    }

    You can't see the backing field in this case, but it's there, provided by the compiler. You don't have to worry about what it's called or where it is.

    You might have noticed at this point that the syntax for the last case is almost the same as the first one, so we have come almost full circle back to where we started. Which might make you wonder why we bothered. Again, ask an Object Oriented Nazi.

    Does any of that help?

    • Proposed as answer by Fei HuModerator Saturday, February 24, 2018 8:03 AM
    Saturday, February 24, 2018 7:59 AM
  • Hello tddyballgm,

    Is there any update or any other assistance I could provide? You could mark the helpful reply as answer if the issue has been solved. And if you have any concerns, please do not hesitate to let us know.

    Thanks a lot.

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, February 26, 2018 9:48 AM
    Moderator