tugberk
tugberk

Reputation: 58494

Cast Object Type value into a Type and get Values out of it by Reflection

The title may not real explains what I need but here is the sample:

This is my model:

public class Car {

    public int CarId { get; set; }
    public string Name { get; set; }
    public string Model { get; set; }
    public string Make { get; set; }
}

Here is the logic:

class Program {

    static void Main(string[] args) {

        var cars = new List<Car> { 
            new Car { CarId = 1, Make = "Foo", Model = "FooM", Name = "FooN" },
            new Car { CarId = 2, Make = "Foo2", Model = "FooM2", Name = "FooN2" }
        }.AsQueryable();

        doWork(cars.GetType(), cars);

    }

    static void doWork(Type type, object value) {

        if (isTypeOfIEnumerable(type)) {
            Type itemType = type.GetGenericArguments()[0];

            Console.WriteLine(
                string.Join<string>(
                    " -- ", itemType.GetProperties().Select(x => x.Name)
                )
            );

            //How to grab values at the same order as properties? 
            //E.g. If Car.Name was pulled first, 
            //then the value of that property should be pulled here first as well
        }
    }

    static bool isTypeOfIEnumerable(Type type) {

        foreach (Type interfaceType in type.GetInterfaces()) {

            if (interfaceType.IsGenericType &&
                    interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                return true;
        }

        return false;
    }
}

what I do here may not make sense but I need this kind of operation somewhere else. I have the a Type and a Object and I need to build a table out of it. In this example, doWork method is pretty same with the one what I am dealing with in my real example.

I managed to pull the property names but I couldn't find any way of retrieving values out of value parameter.

Anyone?

Upvotes: 0

Views: 217

Answers (1)

L.B
L.B

Reputation: 116178

Have you tried something like this?

obj.GetType().GetProperties()
   .Select(pi => new { Name = pi.Name, Value = pi.GetValue(obj, null) })

Upvotes: 1

Related Questions