Get Type Of Class - Create Instance?

M

Mythran

System.Drawing.SystemColors is a class with all static properties. Here is
what my short-ranged goal is...

I want to enumerate all of the SystemColors properties and print the name
(using reflection), and I am able to do this:

PropertyInfo[] props = typeof(SystemColors).GetProperties();
foreach (PropertyInfo prop in props) {
Console.WriteLine(prop.Name);
}


This works fine...now, in the same method, I want to get the value of each
property, which I can using the following:

SystemColors colors = null;
foreach (PropertyInfo prop in props) {
Console.WriteLine(prop.GetValue(null, null).ToString());
}

Now heres the problem, I want to pass the class to the method, so that the
class can be System.Drawing.Colors or System.Drawing.SystemColors, etc...

public static void DisplayColors(object Instance)
{
PropertyInfo[] props = Instance.GetType().GetProperties();
foreach (PropertyInfo prop in props) {
Console.WriteLine(
"Name: {0} - Value: {1}",
prop.Name, prop.GetValue(null, null).ToString()
);
}
}

What do I pass to the DisplayColors method? I can't pass
System.Drawing.SystemColors because it's a not-creatable class? How can I
get a reference to the static instance so I can pass it to DisplayColors?

Thanks,
Mythran
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

What if instead of passing an isntance you pass the type , you could do:

DisplayColors( typeof( SystemColors ));

DisplayColors( some_instance.GetType() );
 
M

Mythran

Ignacio Machin ( .NET/ C# MVP ) said:
Hi,

What if instead of passing an isntance you pass the type , you could do:

DisplayColors( typeof( SystemColors ));

DisplayColors( some_instance.GetType() );

In VB.Net, I was doing the following:

Dim colors As SystemColors
DisplayColors(c)

lol I didn't realize I was still passing NULL! :p So, I changed the
parameter to System.Type and it works :)

Thanks,
Mythran
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top