Home > Back-end >  c# generic constraint when T is class or primitive type
c# generic constraint when T is class or primitive type

Time:03-23

Ok , to simplify we have 2 classes:A,B: both clases have a primary key, called key.

public class A{
String key;
}

public class B{
int key;
}

So we have an interface to manage all entities i called it IRepository, and for this example has only 1 operation:

public interface IRepository<T,TKey> where T: class wher Y:class {
    TKey getKey(T entity);
}

So when i implement this class and finally resolving the generics, in A case good:

public class RepositoryA<A,String> : IRepository<T, TKey>{
 public String getKey(A entity)=> A.key;
}

But in B case obviously not, because int is not an object, so i did a class int wrapper:

public class RepositoryB<B,IntWrapper> : IRepository<B, IntWrapper>{
public String getKey(B entity)=> B.key;
}

Int wrapper just a container of the int value.

 public class IntWrapper{
       int value;
    }

So the question is: can i indicate something like this???

public interface IRepository<T,TKey> where T: class where TKey:class|nonclassvalue 

Or what is the correct way to do what im doing without tricking IntWrapper?

related with this questions:

c# where for generic type constraint class may NOT be

c# generic constraint where is not class?

CodePudding user response:

So the question is: can i indicate something like this???

public interface IRepository<T,TKey> where T: class where TKey:class|nonclassvalue

Sure, just remove the constraint on TKey altogether:

public interface IRepository<T,TKey> where T: class

CodePudding user response:

Just use it without the TKey constraint

public interface IRepository<T,TKey> 
where T: class

Without the TKey:class|nonclassvalue

CodePudding user response:

public interface IRepository<T, TKey>
{
    TKey getKey(T entity);
}

public class RepositoryA: IRepository<A, string>
{
    public string getKey(A entity) {
      return entity.key;
    }
}

public class RepositoryB: IRepository<B, int>{
  public int getKey(B entity)=> entity.key;
}

Is this what you are looking for?

  • Related