Home » C# ProgrammingRSS

Declaring a variable

What is the difference between below two codes?

1.

 private string _shortName;


        public string ShortName
        {
            get
            {
                return _shortName;
            }
  set
            {
                _shortName = value;
            }
        }

and


2. Public string ShortName;

 

2 Answers Found

 

Answer 1

if you have Shortname in a class the use example 1. It makes it safe and uses indexers to access the _shortName field.

You might be able to get away with the second example but eventually it will bite you and is not good.

 

Answer 2

The first is more correct and allow more customization

for example, what if you wanted to override the way that behaves, you can do that with properties but not with public  fields

Also you can add validation logic and creation logic and both the set  and get property can have access levels so as to make the set private  and the get public for example, etc...

There is much more

http://msdn.microsoft.com/en-us/library/x9fsa0sw(VS.80).aspx

Read this

 
 
 

<< Previous      Next >>


Microsoft   |   Windows   |   Visual Studio   |   Follow us on Twitter