Prev | Current Page 392 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"


209 Automatically implemented properties
What do I mean by a trivial property? I mean one that is read/write and that stores
its value in a straightforward private variable without any validation or other custom
code. In other words, it??™s a property like this:
string name;
public string Name
{
get { return name; }
set { name = value; }
}
Now, that??™s not an awful lot of code, but it??™s still five lines??”and that??™s assuming your
coding conventions allow you to get away with the ???one line??? forms of the getter and
setter. If your coding conventions force you to keep member variables in one area of
code and properties in another, it becomes a bit uglier??”and then there??™s the question
of whether to add XML documentation to the property, the variable, or both.
The C# 3 version using an automatically implemented property is a single line:
public string Name { get; set; }
Where previously you might have been tempted to use a public variable (particularly
for ???throwaway code?????”which we all know tends to live for longer than anticipated)
just to make the code simple, there??™s now even less excuse for not following the best
practice of using a property instead. The compiler generates a private variable that
can??™t be referenced directly in the source, and fills in the property getter and setter
with the simple code to read and write that variable.


Pages:
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404