Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Method with Type Constraints

Tags:

c#

.net

I have a set of user controls which are defined like so..

public class Control1: UserControl, Shop.Stock.IBlue

public class Control2: UserControl, Shop.Stock.IBlue

public class Control2: UserControl, Shop.Stock.IBlue

note there are about 200 of these and they are named better in the real project.

I want to write an extension method on objects which are based off UserControl and implement the interface Shop.Stock.IBlue

I don't want the extension method to just be of UserControl

Is there a way of doing this with out adding in a new base class?

like image 742
Jonathan D Avatar asked Feb 21 '23 10:02

Jonathan D


1 Answers

If I'm understanding the question correctly, you want to define an extension method which is only applicable to UserControls which implement IBlue.

   public static void Foo<T>( this T obj )
       where T : UserControl, IBlue
    {

    }
like image 143
Tim M. Avatar answered Mar 06 '23 20:03

Tim M.