//Declare Namespace
using System;
using System.Reflection;
namespace ChangeReadonlyProperty
{
class Program
{
static void Main()
{
DemoClass demoClass = new DemoClass();
Console.WriteLine("String readonly value : {0}", demoClass.GetVal());
FieldInfo fieldInfo = typeof(DemoClass).GetField("strVal", BindingFlags.Instance | BindingFlags.NonPublic);
//User value
Console.WriteLine("Please enter the value");
string strUserval = Console.ReadLine();
//Check and assign default value if null value from the User
strUserval = strUserval == string.Empty ? "No Value" : strUserval;
//Change the read only value with user value
if (fieldInfo != null)
fieldInfo.SetValue(demoClass, strUserval);
Console.WriteLine("User value : {0}", demoClass.GetVal());
Console.ReadKey();
}
}
public class DemoClass
{
// declare the readonly property
private readonly string strVal = "Demo";
// method for get the value
public string GetVal() { return strVal; }
}
}In this code snippet, I explain the how to change readonly properties with reflection.
