Is it possible to indicate that the type used for the general method should be an interface?

Here is my general method code:

public static IT Activate<IT>(string path) { //some code here.... } 

I would like to establish that general IT should only be an interface.

Is it possible?

+6
source share
4 answers

No, there is no such restriction in C # or in general terms. NET in general. You will need to check at runtime.

 if (!typeof(IT).IsInterface) { // Presumably throw an exception } 
+7
source

No, you cannot limit IT any type of interface and interface. The closest thing is that you have a class constraint, and it applies to any class, interface, delegate, or array type. - http://msdn.microsoft.com/en-us/library/d5x73970.aspx

+3
source

The closest thing I can think of is checking the runtime in a static constructor. Like this:

 static MyClass<IT>() { if(!typeof(IT).IsInterface) { throw new WhateverException("Oi, only use interfaces."); } } 

Using a static constructor, we hope, means that it will work quickly, so the developer will detect the error earlier.

Also, the check will be performed only once for each type of IT, and not for each method call. So you won’t get a performance hit.

+1
source

I just did a quick test about using a basic interface. It is possible, but, as I said, not sure if it is worth the effort or even if it is good practice.

 public interface IBaseInterface { } public interface IInterface1 : IBaseInterface { //some code here.... } public interface IInterface2 { //some code here.... } public class Class1 { public void Test() { Activate<IInterface1>("myPath"); //Activate<IInterface2>("myPath"); ==> doesn't compile } public static IT Activate<IT>(string path) where IT : IBaseInterface { //some code here.... } } 
0
source

Source: https://habr.com/ru/post/926961/


All Articles