0

Is there a simple way to have a class with two constructors such as:

public MyClass
{
  public MyClass(object obj)
  {
  }

  public MyClass(List<object> obj)
  {
  }
}

Where instantiating MyClass by passing in a List<int> parameter will cause the List<object> constructor to be used?

It seems this correctly uses the List<object> constructor:

List<object> l = new List<object>();
l.Add(10);
l.Add(20);
MyClass c = new MyClass(l);

But this goes to the object constructor instead of the List<object> constructor:

MyClass c = new MyClass(new List<int> { 10, 20 });

Any idea how to correct this? I'd like to use the List<object> constructor if any List<> is passed in.

Thanks!

joelc
  • 2,687
  • 5
  • 40
  • 60
  • 3
    c# != Java... So you can't . You may indeed use generics, but that not what you are asking... (background reading - https://stackoverflow.com/questions/41179199/cast-genericderived-to-genericbase) – Alexei Levenkov Jun 03 '20 at 23:18
  • Why does your object need to represent both a single object and a list of object? Just have it represent a list of objects that may happen to contain exactly one item in it. – Servy Jun 03 '20 at 23:19
  • 3
    Your problem is that `List` has no conversion to `List` and you can't have a generic constructor. You can, however, have a `static` factory method that is generic. – NetMage Jun 03 '20 at 23:22
  • 2
    That answer that Alexei linked to is really the answer to this. A `List` cannot be casted to `List` because that would allow you add anything to your list. e.g. `obj.Add("somestring")` would work. – Gabriel Luci Jun 03 '20 at 23:28
  • A bowl of apples is something that I can only add apples to. If I could cast it to a bowl of fruit then I could add bananas. But you can't add bananas to a bowl of apples. Likewise you can't cast a `List` to a `List`. – Enigmativity Jun 04 '20 at 01:44
  • Thanks all, seems a static factory may be the way to go. – joelc Jun 04 '20 at 03:54

0 Answers0