Jump to content
  • Advertisement
Sign in to follow this  
JSelf

Pros/Cons for Accessing class members - C#

This topic is 2808 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Those of you who program in C# most likely know of the short cut to creating class properties without private fields, like so:

public int Count
{
get;
set;
}

Obviously, doing so eliminates the need for the programmer to create private fields as VS will do it for you (results in cleaner code, etc). With that said, none of the XNA tutorials I've been reading do so. Plus, they always access the member data through the private field ( _count) instead of the property (this.Count).

I was hoping some more experienced developers could lend some insight as to why. Is it just preference? Or something else that I'm just not aware of?

Also, how do you generally do it? This is assuming, of course, that the members are public and not private/protected.

Thanks for your time.

-Justin

Share this post


Link to post
Share on other sites
Advertisement
IMHO, the code you've posted exhibits a pretty pungent code smell. Empty getters and setters on a public property just makes no sense; make it a public member variable directly and be done with it. Better yet, design your interface such that you don't need to expose state publicly in the first place.

Share this post


Link to post
Share on other sites
Perhaps the tutorials you have been reading were written before C# had automatic properties. It was not part of the language until version 3.0. Personally, I prefer to use the automatic properties unless I want to set a property to a default value without cluttering up the constructor.

Share this post


Link to post
Share on other sites
Another feature of automatic properties


class A
{
public int B { get; private set; }
}


Is causes your set to be private (only the current class can change the value) while allowing outside classes to get the value. Microsoft recommend that [font="'Segoe UI"]for [/font]small classes or structs that just encapsulate a set of values (data) and have little or no behaviors to make the objects immutable by declaring the set accessor as private http://msdn.microsoft.com/en-us/library/bb383979.aspx

Automatic properties just automatically behind the scenes add a private variable then have a default get/set method for that variable. It allows you to later on change it from being automatic to having a custom setter etc. This reduces your code modifications at later stages. i.e. outside classes don't have to be rewritten only the current class.

Share this post


Link to post
Share on other sites
BTW automatic properties are the equivalent to the following just to clarify those who haven't seen this newer language feature.


class A
{
private int x;

public int X
{
get
{
return this.x;
}

set
{
this.x = value;
}
}
}


is equivalent to :


class A
{
public int X { get; set; }
}

Share this post


Link to post
Share on other sites

IMHO, the code you've posted exhibits a pretty pungent code smell. Empty getters and setters on a public property just makes no sense; make it a public member variable directly and be done with it. Better yet, design your interface such that you don't need to expose state publicly in the first place.





You tend to hide interface consumers from changes as much as possible not to break things. You also don't want to expose public member variables very often, unless you're creating simple types such as a Point, or Vector, which for a number of reasons benefit from being as simple as they can, and also exist to merely store state.




It really boils down to the degree of modularity you're aiming for. Automatic properties (which are not "empty") are a commodity for people programming against interfaces.

Share this post


Link to post
Share on other sites
It's already been explained: this syntax is nothing but synthetic sugar. The compiler generates backing fields, and you can verify that with Reflector.

Accessing the backing field directly or its encapsulating property is.. arguable.
If you access directly the field, your code will run a little bit faster, because you won't have to invoke a function, but {get;set;} properties are just 3/4 IL instructions, so your users won't notice any difference.Also, using the property only as a wrapper around the field with no logic attached to it is a little bit too much.
If you access directly your property, and not the backing field, you get the benefit of abstraction. It is common in .NET to have private properties that encapsulate common logic as a field. You can do late initialization, caching of some expensive operation, etc - and the code using that property won't actually care as long as it works.

My preference is to access the property instead of the field. You should have in mind that real-world scenarios sometimes require that you use normal backing fields. For example, some serializers and ORMs use fields and not properties for serialization, and your database/xml storage might end up looking ridiculous.

@ApochPiQ
I am not that competent in game development, but properties are the key to component-driven development. With properties, you can take advantage of ASP.NET's template parser treating properties as attributes/inner elements, thus getting some free serialzation and declarative customization. There are also the property descriptors/converters/validators that enable you to associate a lot of meta information to a property, in effect making your API quite naturally extensible. I, too, agree that having having properties that act solely as public fields with no logic attached to them is a little bit pointless.

Share this post


Link to post
Share on other sites
I have no problem with properties per se; in fact they're very useful for introducing certain types of logic and semantics. But empty properties are worthless.

Consider: in C#, the syntax foo.Field will work to access Field whether Field is a public member or a property. So the best course of action is to begin with public fields, and if you need to refactor to add logic later, drop in a property named Field with the associated logic. No calling code needs to be changed, meaning you only have minor code site updates to make, and everything continues to work swimmingly.

Of course, I stand by my argument that avoiding public state is far superior as a design philosophy anyways.

Share this post


Link to post
Share on other sites

Consider: in C#, the syntax foo.Field will work to access Field whether Field is a public member or a property. So the best course of action is to begin with public fields, and if you need to refactor to add logic later, drop in a property named Field with the associated logic. No calling code needs to be changed, meaning you only have minor code site updates to make, and everything continues to work swimmingly.

The syntax is the same, but the generated MSIL is different. This means that if you change from a public field to property, you can't do a drop in binary replacement. Calling code still needs to be recompiled.

Share this post


Link to post
Share on other sites

[quote name='ApochPiQ' timestamp='1295203640' post='4759727']
Consider: in C#, the syntax foo.Field will work to access Field whether Field is a public member or a property. So the best course of action is to begin with public fields, and if you need to refactor to add logic later, drop in a property named Field with the associated logic. No calling code needs to be changed, meaning you only have minor code site updates to make, and everything continues to work swimmingly.

The syntax is the same, but the generated MSIL is different. This means that if you change from a public field to property, you can't do a drop in binary replacement. Calling code still needs to be recompiled.
[/quote]

Note that the semantics of properties and public variables that return value types are different. For public variables, you are directly accessing the variable. However, a property that returns a value type makes a copy of the variable.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!