It is not possible to convert a type through reference conversion, box conversion, decompression conversion, conversion conversion, or null type conversion

In C #, if I have a parameter for a function where the type of the parameter has an interface, how to make a pass in an object that implements the interface.

Here is an example:

The parameter for the function is as follows:

List<ICustomRequired> 

The list that I already have is as follows:

 List<CustomObject> exampleList 

CustomObject inherits from ICustomRequired

What is the correct syntax for passing exampleList as a parameter?

This is how I decided to complete the above task:

 exampleList as List<ICustomRequired> 

However, I get the following error:

It is not possible to convert a type through a reference conversion, box conversion, decompression conversion, conversion conversion or conversion of a null type

thanks

+5
source share
3 answers

You cannot use a List one type for a List another type.

And if you think about it, you would be glad you couldn't. Imagine the chaos that you could cause if it was possible:

  interface ICustomRequired { } class ImplementationOne : ICustomRequired { } class ImplementationTwo: ICustomRequired { } var listOne = new List<ImplementationOne>(); var castReference = listOne as List<ICustomRequired>(); // Because you did a cast, the two instances would point // to the same in-memory object // Now I can do this.... castReference.Add(new ImplementationTwo()); // listOne was constructed as a list of ImplementationOne objects, // but I just managed to insert an object of a different type 

Please note that this line of code is legal:

  exampleList as IEnumerable<ICustomRequired>; 

This would be safe because IEnumerable does not provide you with any means to add new objects.

IEnumerable<T> is actually defined as IEnumerable<out t> , which means that the parameter is of type Covariant .

Can you change the function parameter to IEnumerable<ICustomRequired> ?

Otherwise, the only option is to create a new list.

 var newList = (exampleList as IEnumerable<ICustomRequired>).ToList(); 

or

 var newList = exampleList.Cast<ICustomRequired>().ToList(); 
+9
source

You cannot do this, you need to convert the list

 exampleList.Cast<ICustomRequired>().ToList(); 
0
source

In addition to List.Cast , C # generators provide good support for covariance and contravariance . This example makes it work as I think it was originally intended.

 public class Program { public static void Main() { Foo(new List<Fim>()); } public static void Foo<T>(List<T> bar) where T : IFim { throw new NotImplementedException(); } public class IFim{} public class Fim : IFim{} } 
0
source

All Articles