Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserControl switch

There are two different UserControls which share some common Properties. What I'd like to do is to switch between these two based on an external flag.

UserControl u1, u2;

if(flag)
{
    u1 = u1 as ControlType1;
    u2 = u2 as ControlType1;
}
else
{
    u1 = u1 as ControlType2;
    u2 = u2 as ControlType2;
}

SomeMethod(u1.SelectedItemName, u2.SelectedItemName);

Since UserControl doesn't have a property called "SelectedItemName", the code would not throw error.

What I've currently done is, I've added an extension method on UserControl which gets the "SelectedItemName" using reflection, and I get the value by calling u1.SelectedItemName() instead of u1.SelectedItemName;

My question is what is an easy way to fix this without using extension/ maybe the right way. Note that I don't want to repeat the SomeMethod(a,b) inside the if statement.

like image 541
edocetirwi Avatar asked Jan 27 '26 07:01

edocetirwi


1 Answers

My suggestion would be to make both of these UserControl classes implement a shared interface or derive from a shared base class. You could then develop against the base class or interface without worrying about the flags/switches at all.

IYourUserControl u1, u2;

SomeMethod(u1, u2);

This would work provided SomeMethod was defined as:

void SomeMethod(IYourUserControl one, IYourUserControl two) { // ...
like image 81
Reed Copsey Avatar answered Jan 29 '26 02:01

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!