Home » C# Programming

Declaring a variable

What is the difference between below two codes?


 private string _shortName;

        public string ShortName
                return _shortName;
                _shortName = value;


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


Read this



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure