0

I am trying to understand the difference between the C# auto declaration of variables with getters & setters & the java declaration.

In java I usually do this:

private int test;

public int getTest() {
    return test;
}

public void setTest(int test) {
    this.test = test;
}

But in C# I tried something like this:

private int test { public get; public set};

But that did not allow access to the variable at all. So I ended up with this:

public int test { get; set; }

So this way I could access the variable test from outside of the class.

My question is, what is the difference between these two? And is the C# implementation of making the variable public a bad idea?

In C# I have declared the variable as "public". Whereas in java it is declared as "private". Does this have any impact?

Found a really good answer (in addition to those below) here

Community
  • 1
  • 1
rtindru
  • 5,107
  • 9
  • 41
  • 59
  • Your first snippet of C# code simply wouldn't have compiled at all - it's not a matter of not allowing access to the variable - it's simply invalid code. – Jon Skeet Jun 25 '13 at 09:09

3 Answers3

3

It is exactly the same.

The automatic property you defined in C# will compile down to getter and setter methods anyway. They are classified as "syntactic sugar".

This:

public int Test { get; set; }

..is compiled to this:

private int <>k____BackingFieldWithRandomName;

public int get_Test() {
    return <>k____BackingFieldWithRandomName;
}

public void set_Test(int value) {
    <>k____BackingFieldWithRandomName = value;
}
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
1

In the first example you have a backing field.

In C# You can do:

private int test { get; set; };

Or make the property public (Perfectly valid)

public int test { get; set; };

You can also have backing fields in C#, these were more common before Properties were introduced in the language.

For instance:

private int _number = 0; 

public int test 
{ 
    get { return _number; }
    set { _number = value; }
}

In the above example, test is a public Property that accesses a private field.

Darren
  • 68,902
  • 24
  • 138
  • 144
  • So when I declare `public int test { get; set; }` the field `test` is private with public getters and setters? Same as in Java? This is what @Simon has said above. – rtindru Jun 25 '13 at 09:11
  • 1
    @rtindru - `test` is a property. Which is public. – Darren Jun 25 '13 at 09:11
  • 1
    @rtindru - if you did `private int test { get; set; }` then `test` would be a private property. – Darren Jun 25 '13 at 09:12
  • @rtindru - I've modified my answer to elaborate slightly more between the fields and properties. – Darren Jun 25 '13 at 09:13
0

Here is the solution, which is provided by the C# compiler to eaisly create getter and setter method.

private int test;

public int Test{
   public get{
      return this.test;
   }
   public set{
      this.test = value;
   }
}
deryck
  • 70
  • 1
  • 3