views:

47

answers:

2

Hi,
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

+4  A: 

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.

Jon Skeet
+1  A: 

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 }); 
}
Paulo Santos