Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c# generic constraint when T is class or primitive type

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading