C # general restriction for type to be thrown

Is there a way with C # generics to restrict the type of T to be hidden from another type?

An example :
Suppose I save the information in the registry as a string , and when I restore the information, I would like to have a function that looks something like this:

 static T GetObjectFromRegistry<T>(string regPath) where T castable from string { string regValue = //Getting the regisstry value... T objectValue = (T)regValue; return objectValue ; } 
+7
generics c #
source share
3 answers

There are no such restrictions in .NET. Only six types of restrictions are available (see Type parameter restrictions ):

  • where T: struct type argument must be a value type
  • where T: class The type argument must be a reference type
  • where T: new() the type argument must have an open constructor without parameters
  • where T: <base class name> the type argument must be or inferred from the specified base class
  • where T: <interface name> type argument must be or implement the specified interface
  • where T: U the type argument provided for T must be or derived from the argument provided for U

If you want to overlay a string on your type, you can cast for the object first. But you cannot set a restriction on the type parameter to make sure that this casting can happen:

 static T GetObjectFromRegistry<T>(string regPath) { string regValue = //Getting the regisstry value... T objectValue = (T)(object)regValue; return objectValue ; } 

Another option is to create an interface:

 public interface IInitializable { void InitFrom(string s); } 

And put it as a restriction:

 static T GetObjectFromRegistry<T>(string regPath) where T: IInitializable, new() { string regValue = //Getting the regisstry value... T objectValue = new T(); objectValue.InitFrom(regValue); return objectValue ; } 
+4
source share

Types are determined at compile time. You cannot change types at runtime. You can expose an object to a base or child class

Ref -

The difference between the object a = new Dog () vs Dog a = new Dog ()

0
source share

Constraints are described as "type T must have type U or inherit type U", so the constraint you are looking for is not enforceable.

still "castable" to String anyway, via .ToString() (YMMV)

0
source share

All Articles