-4

I am admittedly inexperienced with C#/OOP, but I recently came across this code and it feels incorrect to me even though it does appear to functionally work. The code is from a console application.

namespace ConsoleApp
{
  class Program
  {
    static private double Theta{ get; set; }

    static void Main(string[] args)
    {
      ...
      var thetaString = Console.ReadLine();
      if (!String.IsNullOrEmpty(thetaString))
        Theta = Math.PI * Double.Parse(thetaString) / 180.0;
      ...
    }
  }
}

If I remove the static declaration from Theta, it will no longer compile. If I remove the {get; set}, it functions just as it did previously. What is this code doing? What is the significance of the accessors?

M D
  • 217
  • 1
  • 2
  • 6
  • Does it work as expected? If so - it's correct, otherwise it's not. – zerkms Mar 02 '15 at 21:16
  • Why do you feel that this is incorrect? What do you think that it *should* be? – Servy Mar 02 '15 at 21:16
  • 1
    static functions cannot access instance variables, properities etc. – adt Mar 02 '15 at 21:16
  • What is the problem with that? – Hamid Pourjam Mar 02 '15 at 21:16
  • `Theta` is an [auto property](https://msdn.microsoft.com/en-us/library/bb384054.aspx). – chris Mar 02 '15 at 21:16
  • 1
    Yes. The code functions as it says it does. – M D Mar 02 '15 at 21:16
  • 1
    Then it's correct. Case closed. – zerkms Mar 02 '15 at 21:17
  • A static method cannot access instance members (unless of course it has an instance from which to reference the members). That is why you can't remove `static` from the Theta declaration. Without the accessors, you are defining a field, which is a storage location. With the accessors, you are defining a property, which is one or two methods that modify a storage location. The general preference is for properties, though the reasons for that are mostly significant for instance properties rather than static properties. – phoog Mar 02 '15 at 21:17

1 Answers1

1

If I remove the static declaration from Theta, it will no longer compile

That is because you're trying to access an instance property from a static method. You would need to create an instance of Program to access a non-static property.

What is the significance of the accessors?

They allow you do define methods that get/set values rather than just a field that stores a value. There are other more subtle differences, most of which are described here. In my option the most significant are:

  • Changing a field to a property is a breaking change - clients must be rebuilt against the new assembly to incorporate the change. Changing an auto-implemented property to one that has actual code is not a breaking change.
  • Most databinding methods use reflection and only support binding to properties.
Community
  • 1
  • 1
D Stanley
  • 149,601
  • 11
  • 178
  • 240