andrecarlucci
andrecarlucci

Reputation: 6296

How to put an interface constraint on a generic method in C# 3.5?

I want to achieve something like this in C# 3.5:

public void Register<T>() : where T : interface {}

I can do it with class or struct, but how to do it with an interface?

Upvotes: 6

Views: 11671

Answers (4)

Ray
Ray

Reputation: 8834

If possible, I went with a solution like this. It only works if you want several specific interfaces (e.g. those you have source access to) to be passed as a generic parameter, not any.

  • I let my interfaces, which came into question, inherit an empty interface IInterface.
  • I constrained the generic T parameter to be of IInterface

In source, it looks like this:

  • Any interface you want to be passed as the generic parameter:

    public interface IWhatever : IInterface
    {
        // IWhatever specific declarations
    }
    
  • IInterface:

    public interface IInterface
    {
        // Nothing in here, keep moving
    }
    
  • The class on which you want to put the type constraint:

    public class WorldPieceGenerator<T> where T : IInterface
    {
        // Actual world piece generating code
    }
    

Upvotes: 0

Matt Howells
Matt Howells

Reputation: 41266

You can't demand that T is an interface, so you'd have to use reflection at runtime to assert this.

Upvotes: 0

LBushkin
LBushkin

Reputation: 131666

If you are asking about adding a constraint to a specific interface, that's straightforward:

public void Register<T>( T data ) where T : ISomeInterface

If you are asking whether a keyword exists like class or struct to constrain the range of possible types for T, that is not available.

While you can write:

public void Register<T>( T data ) where T : class // (or struct)

you cannot write:

public void Register<T>( T data ) where T : interface

Upvotes: 14

thecoop
thecoop

Reputation: 46098

C# and the CLR don't support overall interface constraints, although you can constrain it to a particular interface (see other answers). The closest you can get is 'class' and check the type using reflection at runtime I'm afraid. Why would you want an interface constraint in the first place?

Upvotes: 5

Related Questions