•  
  •  
  •  
 

Using set and get in C Sharp

Last post 16 Jan 2009, 7:56 AM by loufranco. 1 replies.
Sort Posts: Previous Next
  •  13 Jan 2009, 2:15 PM 17187

    Using set and get in C Sharp

    What is the point of using set and get in C Sharp?

    It seems variables are used differently in this language than in C++.

    For some reason, you have to have a static variable defined like this:

    public static uint Somenum
    {
       set { m_somenum = value; }
       get { return m_somenum; }
    }

    and prior to this declaration, you need to have this:

    public uint m_sumenum;

    This seems to be the only way to expose a member of a class to other classes in C#.

    The problem is that I seem to be doing this improperly because I get a compile error:

    An object reference is required for the non-static field, metod, or property '.......m_somenum"

  •  16 Jan 2009, 7:56 AM 17224 in reply to 17187

    Re: Using set and get in C Sharp

    1. Using get/set allow you to change the behavior of getting and setting later. If you have a field, you can't make something happen when it is assigned or accessed.  For example,

     public static uint Somenum
    {
       set { m_somenum = value; CallOnChangeEventForSomenum(value); }
       get { return m_somenum; }
    }

    public static void CallOnChangeEventForSomenum(uint newValue)
    {
      // do something whenever Somenum is assigned
    }

    2. To get the equivalent field, you need static in the declaration

    public static uint m_sumenum;

View as RSS news feed in XML