1

I came across the question in interview, defining the property in Class. I know this is very basic question but would like to get discuss with experts here.

Method 1:       
       public string MyProperty { get; set; }

Method 2:
       private string _myProperty;
       public string MyProperty 
       {
           get 
           {
               return _myProperty;
           }
           set
           {
               _myProperty = value;
           }
       }

Which will better in performance in terms of extra variable need to declare in Method2.

Liladhar
  • 383
  • 5
  • 20
  • Its not exact duplicate with indicated link. – Liladhar May 28 '16 at 02:28
  • I've changed the duplicate target to be more equivalent to your question (though the original target was likely close enough, anyway). – Rob May 28 '16 at 05:12
  • Cheers, Sometime we cannot find what we exactly want. And only the reason why we need to start new thread. :) anyways Thanks Rob – Liladhar May 29 '16 at 01:58

3 Answers3

3

Both methods use the same number of variables, in the first version the extra variable is just hidden by the compiler, if you decompiled the code you would see it too uses a variable.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
2

Method 1 is a "newer" way of doing things. It was introduced in C# 3.0. Behind the scenes it is in fact using a private backing variable... it's just neater. https://msdn.microsoft.com/en-us/library/bb384054.aspx

Method 2 would probably perform "better" only in the cases where you needed to directly access that variable from within the class itself. But performance wise between the two, it's probably very negligible. You wouldn't need to go through the setter/getter.

However, method 1, in my opinion, just provides a better flow of control, keeps code cleaner, and ensures you're always going through a setter/getter and not directly accessing the private variable itself.

dvsoukup
  • 1,586
  • 15
  • 31
1

Method one is the quick way to implement it and if no extra checks have to be done then that can be used. However, option two is used when you want to sanitize inputs to the class, use security or just want to make sure that he user has to enter something valid as all of your checks can be done in the function before setting the private varible which can be easily canceled in the code.

Shon
  • 486
  • 4
  • 9
  • In case of validating the inputs, we can say it is good to use second. In case suppose property is of Custom Type or Collection type, then while using this property in code we have to instantiate first. Can we instantiate it in property itself? – Liladhar May 28 '16 at 02:24