How to Change Read Only Properties With Reflection

  1. //Declare Namespace  
  2. using System;  
  3. using System.Reflection;  
  4. namespace ChangeReadonlyProperty  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main()  
  9.         {  
  10.             DemoClass demoClass = new DemoClass();  
  11.             Console.WriteLine("String readonly value : {0}", demoClass.GetVal());  
  12.             FieldInfo fieldInfo = typeof(DemoClass).GetField("strVal", BindingFlags.Instance | BindingFlags.NonPublic);  
  13.             //User value  
  14.             Console.WriteLine("Please enter the value");  
  15.             string strUserval = Console.ReadLine();  
  16.             //Check and assign default value if null value from the User  
  17.             strUserval = strUserval == string.Empty ? "No Value" : strUserval;  
  18.             //Change the read only value with user value  
  19.             if (fieldInfo != null)  
  20.                 fieldInfo.SetValue(demoClass, strUserval);  
  21.             Console.WriteLine("User value : {0}", demoClass.GetVal());  
  22.             Console.ReadKey();  
  23.         }  
  24.     }  
  25.     public class DemoClass  
  26.     {  
  27.         // declare the readonly property  
  28.         private readonly string strVal = "Demo";  
  29.         // method for get the value  
  30.         public string GetVal() { return strVal; }  
  31.     }  
  32. }