How can I guarantee that T is a class?

I have the following code:

public static T GetSerializedCopy<T> (T src) { //some code to obtain a copy } 

How can I guarantee that T will be a class and not a structure or enumeration or another?

+4
source share
5 answers

It is very easy to ensure that ...

  public static T GetSerializedCopy<T>(T src) where T : class { //some code to obtain a copy return default(T); } 
+2
source

It is a common mistake (see answers here) to think that adding where T : class to the generic method / type declaration achieves this, but it is wrong. This actually means that " T must be a reference type", which also includes delegates and interfaces (plus arrays, etc., for example string ).

If you need a class, there are two ways; the easiest way is to insist on where T : class, new() , since neither an interface nor a delegate can have constructors. This has false negatives, though, in terms of discarding classes without public constructors without parameters.

The only other way is at runtime:

 if(!typeof(T).IsClass) throw new InvalidOperationException("T must be a class"); 

Equally, where T : struct does not mean that " T must be a value of type", either! This means that T must be a non-nullable value-type "; types with Nullable<> do not satisfy T : struct , even though Nullable<Foo> a struct .

+21
source
 public static T GetSerializedCopy<T> (T src) where T : class 

This is a reference to MSDN for generic type restrictions.

+7
source

you can use Type Constraints on your interfaces. Type restriction

 where T : class 
+2
source

use this:

 where T: class 

Yes..

 public static T GetSerializedCopy<T> (T src) where T : class { //some code to obtain a copy } 
0
source

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


All Articles