Kostub Deshmukh Kostub Deshmukh - 3 days ago 6
Objective-C Question

C#: A method parameter that implements a particular interface

Let's say I have a class called

UIViewController
.

public class UIViewController
{
// ... methods
}


And I have an interface
IDoFancyFlips


public interface IDoFancyFlips
{
// ... methods
}


I have a classes that extend
UIViewController
and implement the interface as follows.

public class FancyViewController : UIViewController, IDoFancyFlips
{
// ... methods
}


Now I want to write a method that takes a
UIViewController
as a parameter, but only ones that implement
IDoFancyFlips
.

public void FlipAndShow(??? controller) {
// implementation
}


My question is what do I put in the ???. I couldn't seem to find any way to do this.

I can do this in Objective C as follows:

- (void) flipAndShow:(UIViewController<IDoFancyFlips>*) controller {
// implementation
}


But I can't find the equivalent declaration in C#.

Answer

You can use generics to accomplish this. Try the following:

public void FlipAndShow<TFancyFlippingController>
       (TFancyFlippingController fancyFlippingController) 
     where TFancyFlippingController : UIViewController, IDoFancyFlips
{
    // implementation
}

The where TFancyFlippingController : UIViewController, IDoFancyFlips constraint ensures that the argument specified for TFancyFlippingController must both inherit from UIViewController and implement the IDoFancyFlips interface.

Comments