Edit:
So after reading OP's answer to my question below, there are several issues here:
Why the code fails?
The reason the code fails is because personName
and personAge
are public fields and not properties, so you should probably use FieldInfo.
What's the difference between a field and a property?
A field is a variable that exists per class instance (per object). It can be modified directly by anyone who has access to that field (depending on the accessibility defined by public
/protected
/private
keywords.
A property in C# can be thought of as a "getter" (and "setter" if defined) functions. Usually (but not always) they provide a layer of abstraction to some private field (also called "backing field"), in order to prevent anyone from modifying that field directly. Instead of having a GetAge()
& SetAge(int age)
methods, we can write:
private int _age
public int Age
{
get
{
return _age;
}
set
{
_age = value;
}
}
Instead of writing this code we can simply write public int Age {get; set;}
(also called auto-properties). this allows us to write code like if(somePerson.Age == 3)
instead of if(somePerson.GetAge() == 3)
, and somePerson.Age = 4
instead of somePerson.SetAge(4)
. It's just a shortcut.
You might ask what's the point of getters and setters and why not simply have a public field and ignore all this non-sense, and the answer is that when you expose a field you have less control over how your class will be used. Let's say that I want a BarMitzvah event to be raised every time someone sets Person
's age to 13, With properties I can change public int age {get; set;}
to:
private int _age
public int Age
{
get
{
return _age;
}
set
{
if(value == 13)
{
RaiseBarMitzvahEvent();
}
_age = value;
}
}
I can't do the same with a public field (unless I change it to a property)
What you should REALLY do
I don't know if you have the time or resources to refactor huge 100 fields large classes, but for the future when writing C# code you should:
- Avoid large classes. Classes shouldn't contain 100 fields (private and definitely not public). You should probably break it to several classes, use composition and follow the Single Responsibility Principle.
- When you want to dynamically set many data points, you probably want to use something like a dictionary rather than many different fields. It's especially true when all your properties are strings and you can simply use
person.SomeDictionaryName[propName] = propValue
.
- Avoid public fields. In almost any case where you use a public field you can use auto-properties (which you should also avoid IMO but that's more subjective)
- When you find yourself using reflection - there's usually a better way to go about what you're doing.
Original
Why not simply:
personInstance.personName = "Some Name";
Why do you need all the extra code and reflection non-sense when the fields are already public? Why have a SetVar
function when you already can set "variables" (actually fields) by simply using the assignment operator (=
)?