lemoos
lemoos

Reputation: 167

retrieve a List of objects from a web service c#

I would like to retrieve a list of objects from my web service ,but I am struggling with Object Types.

I have this code :

 [WebMethod]
    public Car[] GetAllCars()
    {

        List<Car> cars = new List<Car>();
        cars.Add(new Car ("fiat", 1999);
        cars.Add("opel" ,2007);
        cars.Add("chevrolet",2007);
        return cars.ToArray(); // 
     }

When I test the web service from my browser ,everything's fine . it displays me what is should.

But in the client side when I try to do

 MyWebService.WebService1SoapClient cars = new MyWebService.WebService1SoapClient();
        Car[] l = (Car[]) cars.GetAllCars();

it says cannot convert ClientApp.MyWebService.Car[] into ClientApp.model.Car[]

the Car class is the same for the both sides ( client and web service).

What should I do to tackle this problem ?

thank you advance .

Upvotes: 1

Views: 4879

Answers (3)

K.Amine
K.Amine

Reputation: 1

It should work for you:

MyWebService.WebService1SoapClient _cars = new MyWebService.WebService1SoapClient();

public List<Car> Cars;

And in the button event for example :

private void button_valider_Click(object sender, EventArgs e)
    {
        SqlCeConnection connexion =Connexion.getInstance().OpenConnection();
        Cars= new List<Car>();
        Cars= _cars .GetAllCars().ToList();

        foreach (var car in Cars)
        {
            int year= car.year;
             ...

        }

    }

Upvotes: 0

Will
Will

Reputation: 2532

While they may look the same, there are two distinct Car classes involved here:

  1. ClientApp.model.Car - This is the original class, hidden behind the webservice.
  2. ClientApp.MyWebService.Car - This is a near copy, created from the SOAP WSDL

The copy will not have any private members, nor any methods that were part of the original Car.

Simply do this to retrieve the cars, being

var carsWebservice = new MyWebService.WebService1SoapClient();
var cars = carsWebservice.GetAllCars();

This will return an array of ClientApp.MyWebService.Car

Upvotes: 3

Trent
Trent

Reputation: 1381

If the Car is the same on both sides, then there is no reason to cast it and no reason to use a type on the declaration. Let the compiler decide what type to use for l...

var l = cars.GetAllCars();

Upvotes: 2

Related Questions