bflemi3
bflemi3

Reputation: 6790

Get property value type of each value in a class

How can I get the property value type of each property in a class?

this.GetType().GetProperties().ToList().ForEach(p => {
    switch(typeof(p.GetValue(this, null))) {
        case float:
            ...
            break;
        case string:
            ...
            break;
    }
});

This produces the error Cannot resolve symbol p

SOLUTION: I ended up going with LINQ to SQL. Just cleaner and easier to deal :). Thanks Jon

Upvotes: 1

Views: 770

Answers (2)

Sergei Rogovtcev
Sergei Rogovtcev

Reputation: 5832

  1. You can't use switch on Type - it does not have constant values to put in case.
  2. If you still want your switch, and you're working with well-known set of types (i.e., system types), you can use p.PropertyType.GetTypeCode() which returns enum.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500525

I don't get that as a problem - I get:

Test.cs(12,29): error CS1026: ) expected
Test.cs(12,42): error CS1514: { expected
Test.cs(12,42): error CS1525: Invalid expression term ')'
Test.cs(12,44): error CS1002: ; expected
Test.cs(13,9): error CS1525: Invalid expression term 'case'
Test.cs(13,19): error CS1001: Identifier expected
Test.cs(13,19): error CS1525: Invalid expression term ':'
Test.cs(13,20): error CS1002: ; expected
Test.cs(15,9): error CS1525: Invalid expression term 'case'
Test.cs(15,20): error CS1001: Identifier expected
Test.cs(15,20): error CS1525: Invalid expression term ':'
Test.cs(15,21): error CS1002: ; expected

You can't switch on types. Using ForEach like that in general is fine though.

Sample code:

using System;
using System.Linq;

class Test
{
    public string Foo { get; set; }    
    public int Bar { get; set; }

    public void DumpProperties()
    {
        this.GetType().GetProperties().ToList()
            .ForEach(p => Console.WriteLine("{0}: {1}", p.Name,
                                            p.GetValue(this, null)));
    }

    static void Main()
    {
        new Test { Foo = "Hi", Bar = 20 }.DumpProperties();
    }
}

Now admittedly I generally wouldn't use ForEach here - I'd just use a foreach loop:

foreach (var property in GetType().GetProperties())
{
    // Use property
}

Personally I think that's cleaner, simpler to read, and easier to debug.

Upvotes: 1

Related Questions