0

I have a problem. I have a list of companies List<Company>

I need to write a method where I send that list and other lists like List<store> or List<p>...

The point is that I have tried using a method like fillField(List<object> list) but I get an error

the company cannot be converted to object

My question is: do not all of the entities inherit from object?

How do I have to change the method?

Thank you

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
iOSdeveloper
  • 103
  • 11
  • 4
    It seems you have a problem with your code. However, we can't help unless we have [code or information that can reproduce the problem](//stackoverflow.com/help/mcve). Otherwise, we are just blindly guessing. – Blue Aug 04 '16 at 06:25
  • 3
    Depending on what your `fillField` is doing, it might be possible to use a generic method like `fillField(List list) {}` – Stephan Bauer Aug 04 '16 at 06:28
  • the point is I need to use polymorphism. this is the hint – iOSdeveloper Aug 04 '16 at 06:29
  • 1
    Yes - `store` or `p` will inherit from `object` - but that doesn't mean that `List` inherits from `List` ... – marc_s Aug 04 '16 at 06:30
  • 1
    We're not guessing off of "hints". Either tell us all relevant information or don't. That said, call the method like: `fillField(companyList.Cast());` if you think that solves the problem. – Corak Aug 04 '16 at 06:31
  • @ marc_s and how can I make this two to inherit ? – iOSdeveloper Aug 04 '16 at 06:31
  • 1
    The type system won't let you - because `fillField` might try to add a `new Albatross()` to a `List` when in fact what you passed it was a `List` – Damien_The_Unbeliever Aug 04 '16 at 06:34

2 Answers2

1

I think you want to learn about generics. Essentially Generics are used for passing any type you want, such as when you want to serialize (save) the object as a file.

An example on how to use generics:

public void SendListToOtherLists<T> (List<T> listYouWantToSend)
{
    // Your logic...
}

In that example you declared that it's a generic void (it will receive any type as a parameter), and in the parameters you declared that you want to pass a list of any type.

Jakub Loksa
  • 537
  • 1
  • 14
  • 32
0

Yes all objects do inherit object, but you're getting that exception because List<Company> cannot be converted to List<object>. Unless you use .Select to convert Company list to the object list. You have to use a generic function with type parameters:

public void fillField(List<object> list)

Becomes:

public void fillField<T>(List<T> list)