PDA

Click to See Complete Forum and Search --> : [RESOLVED] help checking object type


daimous
Jun 20th, 2007, 11:51 PM
hi guys! i have a method that has one parameter of type object(Pls see the code below) and I know that only objects of a Textbox, Combox, and Listbox are the posible value that i will pass to that parameter. My question is how will i check if the object is Textbox, ComboBox or ListBox. By the way, What im trying to do is to set tha background color of the object that calls the method.


public static void SetCntrlBackColrEnter(object arg)
{

//arg.BackColor = Color.Lavender;
//arg.ForeColor = Color.Black;
}

jmcilhinney
Jun 21st, 2007, 12:03 AM
Your argument should be type Control, not Object. That way you can simply set the ForeColor and BackColor properties without type-checking because both properties are inherited from the Control class.

That said, if you did need to distinguish between types then you'd have several options. The best would be to overload the method, i.e. declare three methods with the same name but different argument types. The system would automatically invoke the appropriate overload for you.

Alternatively you could test the type within the method, e.g.if (arg is ListBox)
{
ListBox lb = (ListBox)arg;
}
else if (arg is TextBox)
{
TextBox tb = (TextBox)arg;
}
else if (arg is ComboBox)
{
ComboBox cb = (ComboBox)arg;
}That's less appropriate though because there's no point using a common method if you're going to do something different in each case.

daimous
Jun 21st, 2007, 01:27 AM
I think,your suggestion to change the type of the parameter object to control is more appropriate. Thanks again!

jmcilhinney
Jun 21st, 2007, 01:56 AM
You should always use the most specific type that you can for your arguments. In this case it's Control because that's the lowest common denominator for the types that are expected. If you were only expecting ListBoxes and ComboBoxes then it would be appropriate to declare the argument as type ListControl, which is the lowest common denominator for those two types.

Don't forget to mark your threads as resolved when you have a solution.

daimous
Jun 21st, 2007, 02:28 AM
Ok..Thanks for the info.