Theoretically I thought I knew the difference between the two. The most crucial difference I thought was that const are baked in where as readonly are decided at the runtime and could be assigned inside the constructor. So, use const only for true constants like numberOfDays etc that's how I thought. Yet, whenever Resharper finds a hardcoded string, it offers to change it to const. Why Resharper? So I wrote a small demo to prove myself what I've been reading or had known is true, I don't know where I screwed up in this demo but my demo doesn't behave as I thought it would!
Below is what I did:
Created a solution
Added two projects (later tried with two solutions as well): A console application and Class library project
The code for console application:
class Program
{
static void Main(string[] args)
{
MessageProvider messageProvider = new MessageProvider();
Console.WriteLine(messageProvider.GetErrorMessage_Const());
Console.WriteLine(messageProvider.GetErrorMessage_Readonly());
Console.ReadKey();
}
}
The code for class library project:
public class MessageProvider
{
private const string ERRORMESSAGE_CONST = "Const: An error occured.";
private static readonly string ERRORMESSAGE_READONLY = "Readonly: An error occured.";
public string GetErrorMessage_Const()
{
return ERRORMESSAGE_CONST;
}
public string GetErrorMessage_Readonly()
{
return ERRORMESSAGE_READONLY;
}
}
The console application references class library project. Then I updated the messages in MessageProvider class, just added a word 'updated' on both const and readonly string. I build the MessageProvider, picked up the new dll from debug folder of the MessageProvider project and replaced the existing MessageProvider.dll in the debug folder of the console application. Then I ran the console application by double clicking the .exe. When the application ran, I could see the updates made to both const and readonly string! I was only expecting to see the updates made to readonly. Where did I misunderstood this topic? What did I do wrong in my demo?