Reputation: 2952
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#.
Upvotes: 2
Views: 77
Reputation: 2608
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.
Upvotes: 4
Reputation: 77896
Considering that all your specific view controller inherits from base UIViewController
class
public class FancyViewController : UIViewController, DoFancyFlips
{
// ... methods
}
public class NormalViewController : UIViewController
{
// ... methods
}
you can check at runtime whether the passed instance is of type DoFancyFlips
and then do the processing further; like
public static void FlipAndShow(UIViewController controller)
{
if (!(controller is DoFancyFlips))
return;
// implementation
}
Upvotes: 0