Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

c# - Why do I need a private field that is exposed via public property?

I'm comming from Java world mainly. So, C# properties do look nice.

I know that with C# 3.0 or above I can use Automatic Properties. I like it even more :).

My question is about a (maybe older) code where I can see this:

   private int age;

   public int Age {

     get { return age; }
     set { age = value; }     
   }

Why do I need the private field age? What I'm I really hiding here?

EDIT:

I completely understand the need for the getter and setter. I mentioned that I'm comming from Java world and doing this all the time.

I do understand that Automatic Properties in C# 3.0 or above are syntatic sugar. But maybe my question has a simpler answer. Does it means that (bellow C# 3.0) the property doesn't hold any value. So it must get the value from some other field?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Older versions of C# didn't have automatic properties, so you had to declare your variables that the properties acted upon like in your example. These days, the same code could be expressed as:

public int Age { get; set; }

I think that answers your question. However, if you are asking "why not just have public int Age; and let programmers set the value on the field directly?", then:

First thing to keep in mind is that property accessors are compiled into methods. This means that it has a different ABI from just reading/writing to a class member variable, even though it may syntactically look the same as if you had:

class Fu {
  public int Age;
}

So, what this means is that if, at some point down the road, you need to add some notification that the Age field has changed - if you are using properties, you can easily add this notification logic to the property setter without breaking ABI.

public int Age {
  get { return age; }
  set { age = value; NotifySomeOtherCode (); }
}

If you start off with a public field, then later changing it to a property will change the ABI which is bad for any program(s) that may depend on your assembly. So it's better to start off with properties.

Hopefully I'm making sense...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...