0

C# makes it relatively easy to get all public properties , or get a property value by name.

But what about setting property values? For a simple test application I would like to be able to do something like this pseudocode which enumerates public properties on a class instance, prompts the user for values, and sets the properties based on these values - converting from input strings to property types as needed:

for(Property p in typeof(instance))
{
 s = ReadLine("Enter the value for {p.Name}, type {p.Type}");
 SetPropertyValue(instance,p.Name, p.Type.parse(s));
}

The major issue I come across that makes a general utility method SetPropertyValue difficult is that Parse doesn't always exist. It does on most basic types but not for string of course or for higher-level types.

I don't mind if it fails on types it doesn't support because my use would basically be int,short,string, byte, etc but how can I employ reflection to knock something up for console mode test apps?

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • 1
    You can probably solve this by using [TypeConverter](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.typeconverter) and `TypeDescriptor`. Maybe the `System.Convert` can be useful here as well. – Leandro Feb 12 '20 at 15:36

1 Answers1

1

@Mr. Boy - something along these lines?:

    ...
    public class Class1
    {
            public int IntProperty { get; set; }
            public string StringProperty { get; set; }
    }
    ...
    var instance1 = new Class1();
    var typeofclass1 = typeof(Class1);
    System.Reflection.PropertyInfo[] listProperty = instance1.GetType().GetProperties();
    var somevalue = "1234";
    foreach(var p in listProperty)
    {
            p.SetValue(instance1, Convert.ChangeType(somevalue, p.PropertyType), null);
    }
yob
  • 528
  • 4
  • 9
  • `typeofproperty` seems to be misnamed. – NetMage Feb 12 '20 at 21:32
  • @NetMage - why? compiles for me just fine. – yob Feb 12 '20 at 21:34
  • Because `typeofproperty` is in fact exactly what the variable __is not__. It is a `PropertyInfo` for the `p.Name` property of `Class1`, so perhaps `propertyInfoForName` or `piFromClass1` would be much better. – NetMage Feb 12 '20 at 21:37
  • 1
    I started to edit and found a second issue - you have `p` already - why are you looking it up again? Just use `p`. – NetMage Feb 12 '20 at 21:42