1

I'm working on a switch statement with Type checking. The following code is working perfectly well for all the types, but, the challenge is with Nullable types.

  switch (Type.GetTypeCode( propertyInfos.PropertyType))
                    {
                        // Type code doesn't have reference with int, long, etc.,
                        case TypeCode.DateTime:
                            // Do the work for DateTime
                            break;
                        case TypeCode.Int32 :
                            // Do the work for Int32
                            break;
                        case TypeCode.Int64:
                            // Do the work for long
                            break;
                        case TypeCode.DateTime? :
                            break;
                        default:
                            break;
                    }

I have tried that to change as GetType and DateTime.Today.GetType().ToString() would give us System.DateTime as a string. But, when used the compiler throws error as that is not a valid Constant string. At any given time instance, DateTime.Today.GetType() would always gives us System.DateTime, why this is not accepted by compiler?

Nabid
  • 197
  • 5
  • 24
  • 1
    You have DateTime twice. The first case and the last non-default case are both DateTime. The message is "The switch statement contains multiple cases with the label value '16'". Voting to close. – ProgrammingLlama Nov 29 '17 at 04:46

2 Answers2

2

I found this clever solution using a dictionary instead of a switch. Using that method, this should work for you:

public class Test {
    public DateTime A { get; set; }
    public Int32 B { get; set; }
    public Int64 C { get; set; }
    public DateTime? D { get; set; }
}

...Main...
        var @switch = new Dictionary<Type, Action> {
            { typeof(DateTime), () => Console.WriteLine("DateTime") },
            { typeof(Int32), () => Console.WriteLine("Int32") },
            { typeof(Int64), () => Console.WriteLine("Int64") },
            { typeof(DateTime?), () => Console.WriteLine("DateTime?") },
        };

        foreach (var prop in typeof(Test).GetProperties()) {
            @switch[prop.PropertyType]();
        }
Neal Ehardt
  • 10,334
  • 9
  • 41
  • 51
0

I have used Nullable.GetUnderlyingType Method. I have applied type checking for nullable type then identified the nullable type and then finally specified the nullable's generic type.

if (Nullable.GetUnderlyingType(propertyType) != null)
            {
                // It's nullable
                Console.WriteLine(propertyType.GetGenericArguments()[0]);

            }
Nabid
  • 197
  • 5
  • 24