0

I have the following classes.

Car.cs

public class Car 
    {
   
   }

scoda.cs

public class scoda : Car
    {
   
    }

Test.cs

 public class Test
    {
       public ObservableCollection<scoda> scodaList;
        public Test()
        {
            scodaList = new ObservableCollection<scoda>();
            scoda s = new scoda();
            scodaList.Add(s);
            set(scodaList);
        }

        public void set(ObservableCollection<Car> list)
        {

        }
    }

I got the casting error when calling set method as below

Cannot convert from 'System.Collections.ObjectModel.ObservableCollection<KillCarMain.deneme.scoda>' to 'System.Collections.ObjectModel.ObservableCollection<KillCardMain.deneme.Car>'

How to fix this problem ?

şahin
  • 19
  • 3
  • A list of Scodas is not a list of cars. Think about what would happen if you add a Ford to the list from within the set method. For further informataion, look up "covariance". – Klaus Gütter Nov 10 '22 at 14:20
  • Does this answer your question? [C# variance problem: Assigning List as List](https://stackoverflow.com/questions/2033912/c-sharp-variance-problem-assigning-listderived-as-listbase) – Klaus Gütter Nov 10 '22 at 14:22

1 Answers1

0

As pointed out in the comment, a collection of Car is not a collection of Scoda. So you should convert your collection of Scoda into a collection of Car:

var carList = new ObservableCollection<Car>(scodaList.Select(s => (Car)s));
set(carList);

If you don't want to create a new ObservableCollection, you could define scodaList as a collection of Car objects:

public ObservableCollection<Car> scodaList;

private void test() 
{
    scodaList = new ObservableCollection<Car>();
    scoda s = new scoda();
    scodaList.Add(s);
    set(scodaList);
}
public void set(ObservableCollection<Car> list)
{

}
Alessandro
  • 116
  • 6
  • In this solution new instance of Observable collection is creted. How to send observable collection to the method by reference ? I want to keep observable collection reference in the set method. – şahin Nov 11 '22 at 06:35
  • @şahin I edited the answer. I hope it helps. – Alessandro Nov 11 '22 at 07:57