TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
How to Change Read Only Properties With Reflection
Jitendra Kumar
Aug 09
2016
Code
10.8
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
//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