Ashish Gupta
Ashish Gupta

Reputation: 15139

Read-only variables VS read only properties

public static string BoldStartTag { get { return "<B>"; } }

VS

   public static readonly string BoldStartTag  = "<B>"; 

or

public const string BoldStartTag  = "<B>"; 

which one is preferred? I would think the readonly/constant variable as I am not doing any computation in the property (just return). Also, the C# compiler will eject a method for the readonly property whereas the readonly variable will just be a variable in the IL.

Your thoughts?

Upvotes: 8

Views: 2022

Answers (3)

David Hedlund
David Hedlund

Reputation: 129832

Jeff Atwood wrote an article on Properties vs Public Variables a while back.

I think some of the most interesting points to consider here are the ones he mentions in his update:

  • Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
  • You can't databind against a variable.
  • Changing a variable to a property is a breaking change.

Upvotes: 9

zildjohn01
zildjohn01

Reputation: 11515

The preferred method for public values is always a property, for encapsulation reasons.

For your specific example, though, I'd use a const -- it's not like BoldStartTag will be changing any time soon.

Upvotes: 4

Hans Olsson
Hans Olsson

Reputation: 55059

Why not use const? I would have thought that having <B> as the bold start tag would be fairly set in stone.

Upvotes: 1

Related Questions