This is a mirror of official site: http://jasper-net.blogspot.com/

To const or to not to const (static readonly) that is the question

| Tuesday, December 21, 2010
Lets discuss the following scenario:

We have an assembly named [DomainModel] that has a class named [Person] that all of its properties are stored in a property-bag, in addition we have a const string that holds the key of the Name Property, this key is named [NameKey] and Its value is “Name”, so far so good.  

don’t ask me why I use property bag this is just for demonstration purposes only.

namespace DomainModel
{
   public class Person
   {
       public const string NameKey = "Name";

       public Person()
       {
           PropertyBag = new Dictionary<string, object>();
       }

       public Dictionary<string,object> PropertyBag { get; set; }
   }
}
the problem starts when a different assembly, PersonBL in our case, uses Person.NameKey in order to set the Name value

public Person GetPerson()
{
   var person = new Person();
   person.PropertyBag[Person.NameKey]="Tal";
   return person;
}
everything works fine until one changes the value of the const field from “Name” to “FullName”,
if you rebuild all of the assemblies there is no problem, however if you complied only [DomainModel] and tried to run the application than you will have a KeyNotFoundException

Read more: Tal Pasi

Posted via email from .NET Info

0 comments: