tags:

views:

978

answers:

4

Is there some internal difference between the C# syntactic sugar way of making properties:

public string FirstName { get; set; }

and just making public variables like this:

public string LastName;

I assume the first way is preferred and the second to be avoided. However, I often see this type of readonly property being used which is a form of the second type above:

public readonly string InternalCode;

Is this a best-practice way to create readonly property?

using System;

namespace TestProps
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer();
            customer.FirstName = "Jim";
            customer.LastName = "Smith";
            customer.Show();
        }
    }

    class Customer
    {
        public string FirstName { get; set; } //prefered
        public string LastName; //avoid
        public readonly string InternalCode; //???

        public Customer()
        {
            InternalCode = "234729834723984";
        }

        public void Show()
        {
            Console.WriteLine("{0}, {1} ({2})", LastName, FirstName, InternalCode);
            Console.ReadLine();
        }
    }
}
A: 

Yes. it is OK to have a public readonly variables (it is just that they can be initialized at the time of definition or constructor).

e.g. Decimal.MaxValue

Having public readonly property is good, if the backing value changes (other than what it was initialized with).

e.g. Environment.TickCount

I thought that Environment.NewLine will be a public readonly variable. Well, it is a public property (get only) and the reason could be to maintain compatibility across different platform.

shahkalpesh
What is wrong with this? Please post the reason when down-voting. It will help me realize my mistake. Thanks.
shahkalpesh
No vote from me, but actually Decimal.MaxValue is a const and not an instance field (Read the article by Jon Skeet linked in my answer for reasons not to expose fields)
0xA3
+1  A: 

Using a property provides an interface which more resistant to change in the future. Let's say some time in the future, a decision is made to add a prefix to the internal code.

Using a public readonly variable exposes your internal structure and you will have a hard time adding the prefix to every line you used the internal variable of the class.

Using a Property, you can just write the following

public string InternalCode { 
    get { return _prefix + _internalCode; } 
}

and you're done!

Michael Barth
once you resolve all your compiler errors :-)
Greg Dean
What compiler errors?
Michael Barth
Error 1 The modifier 'readonly' is not valid for this item
Greg Dean
Ah, just noticed it! Sorry, copy/paste error ^^'
Michael Barth
+2  A: 

In my opinion, it's ok to expose public fields (especially if they're readonly or const). Having said that, I'd say that in the example you're presenting, I'd probably go with properties since they'll give you 2 advantages (over fields): 1) better encapsulation and may let you adapt your code in the future and 2) if you're doing data binding, then you do need the properties.

Luis Abreu
+5  A: 

Since he didn't answer (yet) and no one else referenced this yet: There is a great article on this topic by Jon Skeet amending his book C# in depth (give credits to Jon):

Why Properties Matter

0xA3
that article was a two pages directly addressing my question, thanks! I understand from it that Jon would not even approve of "public readonly bool IsValid;" unless, as he mentions at the end, it is in a nested class
Edward Tanguay