Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read-only variables VS read only properties

Tags:

c#

oop

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?

like image 954
Ashish Gupta Avatar asked Jun 01 '10 09:06

Ashish Gupta


1 Answers

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.
like image 157
David Hedlund Avatar answered Oct 18 '22 03:10

David Hedlund