Nick’s Code

Search

XNA MVP

Contact

Donate

Categories

Latest News

Twitter


follow nickgravelyn at http://twitter.com



RSS Feed

Let’s Talk C# Features, Pt 1.5

Posted in .NET, C#, XNA on May 13, 2008 at 12:00am.
There are 4 comments.

So the one part of the auto-implemented features I forgot to touch on was how you can make this better than just public fields. Let’s look at two versions of a class, one using auto-implemented properties and one with public fields. First our auto-implemented property version.

public class MyClass
{
	public float Value { get; set; }
	public string AnotherValue { get; set; }
	public bool SomethingElse { get; set; }
}

And now our public field version:

public class MyClass
{
	public float Value;
	public string AnotherValue;
	public bool SomethingElse;
}

Well now it looks like we’re getting the shaft with our properties, right? Not quite. Let’s say you suddenly decide that the Value property should be set through a constructor. This means it has to be get-only to the outside world. This is easy with auto-implemented properties since you can tack on an access modifier to the set property inside of there. So to make Value read-only, our class now looks like this:

public class MyClass
{
	public float Value { get; private set; }
	public string AnotherValue { get; set; }
	public bool SomethingElse { get; set; }

        public MyClass(float value)
        {
               Value = value;
        }
}

And for our public field version? Well we could decide we were wrong and switch to auto-implemented properties, or we can do this the old fashion way. We’d mark our field as ‘private’ and add a get-only property to the class (as well the constructor like above).

public class MyClass
{
	private float value;
	public string AnotherValue;
	public bool SomethingElse;

        public float Value
        {
                get { return value; }
        }

        public MyClass(float value)
        {
               this.value = value;
        }
}

So we see that auto-implemented properties are not only almost as short as public fields, but you can quickly turn them into read-only properties with much less code than our field version.



By Aphid on May 14, 2008 at 8:48 am

Should the constructor not read “this.value = value;”?

By Nick on May 14, 2008 at 8:49 am

Indeed. Thanks. I’ve changed it above.

By GoldenCrystal on June 15, 2008 at 6:49 am

Even better than implementing yout own property, you could just use the readonly keyword ;)
No real advantage for C# 3.0 here

By Nick on June 15, 2008 at 9:30 am

Only if you want to set the value in the constructor. Sure my example would work as readonly, but if it’s readonly, I can’t change the value any time later. By having the private property, my class can change that value at any time. So there is a difference between having the readonly field and the public get/private set property.



Post A Comment