Um, How do these work?
I know you do something like

Blah Blah {Get; Set;}

but how does that work? how does it know what to get and set?

Edited 5 Years Ago by majorawsome: n/a

majorawsome
Deleted Member

The C# compiler is very smart!
It fills in the details for you.
Internally it creates a private field Blah and expands the get and set in a normal way.
It is just shorthand invented to make life easier, if you have to create a 100 or more of these properties, this syntax comes in handy. Let the compiler do tha work!

Never mind Sodabread, I would have loved to see your answer :)
And by the way, this syntax only works if you have a simple property.
If you do some data validation in the set field part or something else, you have to use the normal syntax.

how does it know what to get and set?

Magic. The compiler basically turns it into this:

Blah __anonBlahBlah;
Blah Blah {
    get { return __anonBlahBlah; }
    set { __anonBlahBlah = value; }
}

1st time you SET it.
2nd time oyu get it.

Simple. If you want to read, 1st you have to set it, then when is set, you can ge it.

Example:

class a1
{
     a2 a;
     private void methodA()
     {
          a = new a2();
          a.MyText = "something to set"; //set
     }

     private void methodB()
     {
          string text = a.MyText; //get
     }
}

class a2
{
     public string MyText { get; set; }
}

So If i do this it would work?

Class Thingy
    Int k = 56;
    Int j {get; set;}

What if i had two variables?

class thingy
    int i = 9;
    int o = 8;
    int u = { get{i}; set;}

is that how it would work?

Do you want to set "u" property to field "i"?
If so, you can do it this way:

int i = 9;
int o = 8;

private U;
int u
{
    get { return U; }
    set { U = i; }
}

If you will get i in u property (like you showed), then there is no point in having u property at all.

Ok. but what about the return? shouldn't it be i because that is the integer we want

public String proxyusername= "sam";
public String proxyuname
        {
            get
            {
                return proxyusername;
            }
            set
            {
                proxyusername= value;
            }
        }

//GET
when the value of proxyuname is called like

string name = proxyuname;

then the properties get the value of proxyusername and returns.
//SET
when the value of proxyuname is assigned or changed it seta the value to proxyusername.

proxyuname = "samueal";

Ok that cleared it up. Thanks

If using VS2010...

Remember, you can set the cursor on a variable, and in the right-click menu select Refactor->Encapsulate Field.

Visual Studio 2010 does all the work for you :)

We use it in a c# properties for set and get private members.

Edited 5 Years Ago by __avd: Snipped URL

This article has been dead for over six months. Start a new discussion instead.