C# Corner
Tech
News
Videos
Forums
Trainings
Books
Live
More
Interviews
Events
Jobs
Learn
Career
Members
Blogs
Challenges
Certifications
Bounties
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
How to Change Read Only Properties With Reflection
WhatsApp
Jitendra Kumar
Aug 09
2016
12.9
k
0
0
//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; }
}
}
C#
Reflection
Up Next
How to Change Read Only Properties With Reflection