0

I need to determine the property type of a class's properties at runtime so that I can perform data conversion before assignment. I've seen a bunch of answers on SO, such as:

Using PropertyInfo to find out the property type

But clearly I must be doing something wrong because the following test code always drops to the default case:

public class MyClass
{
    public int? Id { get; set; }
    public string Seller { get; set; }
    public DateTime? PaymentDate { get; set; }
    public double? PaymentAmount { get; set; }
    public string PaymentMethod { get; set; }
}....

And the test code.

string s = "";
PropertyInfo[] propertyInfos = typeof(MyClass).GetProperties();
...
    foreach (PropertyInfo propertyInfo in propertyInfos)
    {
        switch (propertyInfo.PropertyType)
        {
            case Type _ when propertyInfo.PropertyType == typeof(string):
                    s = "It's a string!";
                break;
            case Type _ when propertyInfo.PropertyType == typeof(int):
                    s = "It's an int!";
                break;
            case Type _ when propertyInfo.PropertyType == typeof(double):
                    s = "It's a double!";
                break;
            case Type _ when propertyInfo.PropertyType == typeof(DateTime):
                s = "It's a datetime!";
                break;
            default:
                ...
                break;
        }
    }
...

There is a propertyInfo returned for Id, Seller ,etc..., but nothing matches in the switch. I simply need to identify the type of each property in the class.

I also tried using TypeCode, but also no luck as variable tc always has the value of object, not sure why:

Type pt = propertyInfo.PropertyType;
TypeCode tc = Type.GetTypeCode( pt );

switch (tc)
{
    case TypeCode.DateTime:
        s = "DateTime";
        break;
    case TypeCode.Int32:
        s = "Int";
        break;
    case TypeCode.String:
        s = "String";
        break;
    default:
        s = "string";
        break;
}

What am I doing wrong in either of those two approaches?

BarnumBailey
  • 391
  • 1
  • 4
  • 13

1 Answers1

-1

In your class you have properties like

public int? Id { get; set; }

But in your switch you are checking this case

case Type _ when propertyInfo.PropertyType == typeof(int):

and the problem is that typeof(int?) != typeof(int)

You need to add cases for your nullable types.

TJ Rockefeller
  • 3,178
  • 17
  • 43
  • Ugh.... and double ugh... yes it was the fact that the properties were nullable. Thank you for the prompt response - and excellent eyes. :) – BarnumBailey Mar 22 '22 at 18:30