0

I have been programming for a while now but am relatively new to c#. Long story short, I need to do the following:

public abstract class SomeBaseClass
{

}

public class SomeSmallClass<T> where T : SomeBaseClass
{

}

private List<SomeSmallClass<SomeBaseClass>> listOfData = new List<SomeSmallClass<SomeBaseClass>>();

public void AddToList<T>() where T : SomeBaseClass
{
   listOfData.Add(new SomeSmallClass<T>());
} 

This gives a nasty red underline and a compiling error that reads "Cannot Implicitly convert SomeSmallClass to SomeSmallClass".

What I don't understand is why the compiler doesn't know that T will always be a SomeBaseClass. Does anyone know what's happening here?

Note: there is no problem with instancing the SomeSmallClass only with adding it to the list.

Any help is much appreciated.

Elliott
  • 39
  • 3
  • The error is not `Cannot Implicitly convert SomeSmallClass to SomeSmallClass` it's actually `Cannot convert from SomeSmallClass to SomeSmallClass` which seems to make sense, [they are not the same](https://stackoverflow.com/a/1817341/14868997). – Charlieface Jun 17 '22 at 16:01
  • There error does say implicitly but I can't convert at all because doing so (even in a custom converter) would loose data that I am trying to preserve. I need a way that works without this kind of casting. – Elliott Jun 17 '22 at 16:05
  • See fiddle https://dotnetfiddle.net/crmXqt is that your code? You don't need to convert, you need to use covariance – Charlieface Jun 17 '22 at 16:06
  • Thanks for taking the time to help. Yes that is my code. After reading up on covariance I believe I understand the idea. I still don't understand how it could help beyond what is already being done. Could you maybe demonstrate your idea? – Elliott Jun 17 '22 at 16:15
  • Problem is how does the compiler know that it's safe to assign a `SomeSmallClass` to a variable `SomeSmallClass x`. What would happen if you did that and then someone tried to do `x.Add(OtherDerivedObject)`? So to prevent that you cannot do this, unless you use covariance. Then the compiler knows that `T` can only appear in an `out` position, and therefore is always safe. This is why you cannot convert `List` to `List`, but you *can* convert `IEnumerable` to `IEnumerable` – Charlieface Jun 17 '22 at 18:41

0 Answers0