Refael
Refael

Reputation: 7353

Get all types of properties for an object

I have an object with some types of properties:

public class MyClass
{
    public List<SomeObj> List { get; set; }
    public int SomeKey { get; set; }
    public string SomeString { get; set; }
}

var obj = new MyClass();

What is the best way to get all types of properties for obj instance of the MyClass ?
For example:

obj.GetAllPropertiesTypes() //int, string, List<>
obj.HasPropertyType("int")  //True

Upvotes: 0

Views: 1350

Answers (1)

Zein Makki
Zein Makki

Reputation: 30052

Using Reflection:

var obj = new MyClass();

foreach (var prop in obj.GetType().GetProperties())
{
    Console.WriteLine($"Name = {prop.Name} ** Type = { prop.PropertyType}");
}

Result:

Name = List ** Type = System.Collections.Generic.List`1[NameSpaceSample.SomeObj]
Name = SomeKey ** Type = System.Int32
Name = SomeString ** Type = System.String

If you're looking for more user-friendly type names, see this.

As for Has property of a specific type, then:

bool hasInt = obj.GetType().GetProperties().Any(prop => prop.PropertyType == typeof(int));

Upvotes: 2

Related Questions