Dynamically change the value of public variable using reflection in c#
Once i was working on asp.net project and i got a little task that i need to change the values of Blank public variables, i was having two way of doing this one was to set each variable value manually or other is by using reflection, i did little Google, and then created a method that replace the value of each public variable of type string.//this1 is the any class object and you want to replace the values of public string variables of this object
public void ReplaceBlankValues(object this1)
{
//MemberInfo array will hold all public variables of class
MemberInfo[] properties = this1.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
if (property.ToString().Length > 13)
{
string type = property.ToString().Substring(0, 13);
if (type == "System.String" && property.MemberType.ToString() != "Method")
{
Type typeInQuestion = this1.GetType();
//Field info containthe information of variable
FieldInfo field = typeInQuestion.GetField(property.Name);
string value = Convert.ToString(field.GetValue(this1));
if (value == "")
{
//Here i am replacing the value of field to "$nbsp;"
//In SetValue method you need to pass current object and the value to replace existing value
field.SetValue(this1, " ");
}
}
}
}
}
Comments
Post a Comment