2

I have a class that parses stringified data into native data types (properties on itself). It iterates through the class properties and uses a switch statement that matches on the property type:

using System.Reflection;

…

class DataParser
{
    public int i { get; set; }
    public bool b { get; set; }
    public string s { get; set; }
    public DateTime d { get; set; }
    public Decimal e { get; set; }

    public DataParser()
    {
        PropertyInfo[] properties = this.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
            object currentValue = property.GetValue(this);
            switch (currentValue)
            {
                case Int32 _:
                    …
                    break;
                case DateTime _:
                    …
                    break;
                case Decimal _:
                    …
                    break;
                case Boolean _:
                    …
                    break;
                case string _:
                    …
                    break;
                default:
                    throw new Exception($"Could not find type for {property.PropertyType}");
            }
        }
    }
}

Type matching works for all types except string, which throws with:

Exception: Could not find type for System.String

Perhaps it's not matching because string is a reference type? I've substituted the string case for String and System.String, same result.

UPDATE

As some folks suggested, the value of the string property was null. Setting a default value

public string s { get; set; } = "";

caused it to match.

kja
  • 101
  • 1
  • 5

0 Answers0