mardi 30 juin 2020

C#: How to set an Object's member by passing it a variable name and value

I have a class with a lot of properties (all Strings). I dynamically receive the name (and value) of a property to be set. Don't want to do a 100 if-then's to set the right variable. Would like to call something like:

Person.setVar(string propname,  string propvalue)

I have tried the following (based on my limited understanding through various posts here on SO):

using System;
using System.Reflection;

namespace MiscTest {
    public class Person {
        public string personName;
        public string personAge;

        public void SetVar(string propName, string propValue) {
            PropertyInfo propInfo = this.GetType().GetProperty(propName);
            propInfo.SetValue(this, propValue, null); //<--error here
        }
    }
}

However, keep running into this error ... something about Object reference not set:

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at MiscTest.Person.SetVar(String propName, String propValue) in C:\<long-path>\PropertyTest.cs:line 13

Any idea of what I might be doing wrong?





Aucun commentaire:

Enregistrer un commentaire