C# property sugar


Sometimes I give myself a hard time for being slow … (yes mentally, dammit how come I am not a genius!?!? genes oh genes, maybe I was dropped on my head .. or my mother smoked a spliffy laced with shoe polish at the critical point my cortex was developing). I try to make up my lack of genius with persistence and focus. This post should of happened when C# 3.0 was released, not now when we are using C# 4.0. I guess it is better to learn something late then not learning it at all. Yeee hawwwww!

Back in the day until recently, I defined my class properties like this:

public class NewObject
{
        private int _property1;
        private Object _property2;
        private string _property3;

        public int Property1
        {
            get
            {
                return _property1;
            }
            set
            {
                _property1 = value;
            }
        }

        public Object Property2
        {
            get
            {
                return _property2;
            }
            set
            {
                _property2 = value;
            }
        }

        public string Property3
        {
            get
            {
                return _property3;
            }
            set
            {
                _property3 = value;
            }
        }
}

Now I define them with this great syntactical sugar!

 public class NewObject
 {
        public int Property1 { get; set; }
        public Object Property2 { get; set; }
        public string Property3 { get; set; }
 }

You can even use access modifiers on them. Ohh… look.. NewObject is so private about setting her members now:
 public class NewObject
 {
        public int Property1 { get; private set; }
        public Object Property2 { get; private set; }
        public string Property3 { get; private set; }
 }

She was probably sick of being treated like an Object *snicker*.
I use this exclusively now, it makes the code more readable. However there is no performance or compiled code benefits, still looks the same behind the scenes.

Later, I hope I saved you some screen space for all you old skool .Net Hackers!

Check out this band Divinity



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.