Ruben
Ruben

Reputation: 139

Change type of control by type

I'm having following problem.
I should convert a control to a certain type, this can be multiple types
(for example a custom button or a custom label, ....)
Here's an example of what i would like to do:

private void ConvertToTypeAndUseCustomProperty(Control c)
{
     Type type = c.getType();
     ((type) c).CustomPropertieOfControl = 234567;
}

Thanks in advance

Upvotes: 0

Views: 480

Answers (2)

Paulo Santos
Paulo Santos

Reputation: 11567

Although C#, before 4.0, doesn't support dynamic type resolution as VB does, it can be achieved with a little bit of reflection.

private void ConvertToTypeAndUseCustomProperty(Control c) 
{ 
   PropertyInfo p = c.GetType().GetProperty("CustomPropertieOfControl"); 
   if (p == null)
     return;
   p.SetValue(c, new object[] { 234567 }); 
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500335

Is it fair to assume that you control the types which have "CustomPropertyOfControl"? If so, make them all implement an interface, and cast to that interface.

The point of a cast is to tell the compiler something you know that it doesn't - at compile time. Here you don't know the type at compile time. If you know some base class or interface, then you can tell the compiler that with no problem.

Now in C# 4 you could do this using dynamic typing:

private void ConvertToTypeAndUseCustomProperty(Control c)
{
    dynamic d = c;
    d.CustomPropertyOfControl = 234567;
}

However, even though you can do this, I'd still recommend sticking with static typing if at all possible - if you've got a group of types which all have some common functionality, give them a common interface.

Upvotes: 4

Related Questions