Why doesn't System.Guid implement System.IConvertible?

I recently tried to return an object of type Guid from a method accepting <T> , however the compiler gave me the following error

The type 'System.Guid' cannot be used as a parameter of type 'T' in the generic type or method "MyGenericMethod". No boxing conversion from 'System.Guid' to 'System.IConvertible' .

After researching, I realized that the compiler message was caused by the fact that the Guid type did not implement the System.IConvertible interface.

MSDN states the following:

This interface provides methods for converting an instance value to an implementation type for a common runtime type that has an equivalent value.

The provided list of types does not include Guid; Can someone explain / provide a usage example why this is so?

+4
source share
2 answers

IConvertible requires that a type can convert data to most primitives. How do you imagine Guid as a float, for example?

Because Guid cannot implement most of the interface methods that he expected did not declare otherwise.

Now for the real question: what are you trying to accomplish?

+11
source

Using System.Guid as type parameters for generic methods is not a problem, as the following code shows. Can you post the implementation of the MyGenericMethod method, as well as the code that calls this method?

 class Program { static void Main(string[] args) { var test = new GenericTest(); test.MyGenericMethod(Guid.NewGuid()); } } class GenericTest { public void MyGenericMethod<T>(T t) { } } 

I assume that the method implementation has a type constraint that requires the type parameter to be IConvertible, and therefore looks something like this:

 class Program { static void Main(string[] args) { var test = new GenericTest(); test.MyGenericMethod(Guid.NewGuid()); } } class GenericTest { public void MyGenericMethod<T>(T t) where T : IConvertible { } } 
+1
source

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


All Articles