Reputation: 899
I have the following setup:
public interface IInput
{
}
public class SomeInput : IInput
{
public int Id { get; set; }
public string Requester { get; set; }
}
Now I want to write a function that can take anything that implements IInput and use reflection to give me the properties :
public Display(IInput input)
{
foreach (var property in input.GetType().GetProperties())
{
Console.WriteLine($" {property.Name}: {property.GetValue(input)}");
}
}
Where
var test = new SomeInput(){Id=1,Requester="test"};
Display(test);
shows
Id: 1
Requester: test
Upvotes: 0
Views: 1482
Reputation: 52240
If you use typeof()
you get the type of the variable. But if you use GetType()
you get the actual runtime type, from which you can reflect all implemented properties.
void DumpProperties(IInput o)
{
var t = o.GetType();
var props = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var prop in props)
{
Console.WriteLine(String.Format("Name: {0} Value: {1}",
prop.Name,
prop.GetValue(o).ToString()
);
}
}
Upvotes: 2