locked
Unknown type being passed RRS feed

  • Question

  • Hello,

    I have the following method:

    Chart Build(List<Int32> x, List<List<Int32>> y);

    But x can be an Int32, a DateTime, etc ..

    Is there a way to generalize the type that is being passed?

    I tried to use List<Object> or List<Type> but when I call the method with List<Int32> or List<DateTime> I get an error.

    Thank You,

    Miguel

    Thursday, February 23, 2012 5:57 PM

Answers

  • It depends on how you're using it -

    You can always make a method using generics, ie:

    Chart Build<T>(List<T> x, List<List<int>> y)

    However, this may be difficult to use depending on what you're trying to do within the method.  How does the different types of "x" objects change what you'll do inside of the method?

    With C# 4, you could use variance here for your X - instead of using List<T>, if you use IEnumerable<T>, you can use:

    Chart Build(IEnumerable<object> x, List<List<int>> y)

    If this is only being used for the names along the X axis, you could also just pass IEnumerable<string>, and use LINQ to convert the obejcts (via Select) to string...


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Proposed as answer by servy42 Thursday, February 23, 2012 6:29 PM
    • Marked as answer by MDMoura Thursday, February 23, 2012 6:31 PM
    Thursday, February 23, 2012 6:00 PM

All replies

  • It depends on how you're using it -

    You can always make a method using generics, ie:

    Chart Build<T>(List<T> x, List<List<int>> y)

    However, this may be difficult to use depending on what you're trying to do within the method.  How does the different types of "x" objects change what you'll do inside of the method?

    With C# 4, you could use variance here for your X - instead of using List<T>, if you use IEnumerable<T>, you can use:

    Chart Build(IEnumerable<object> x, List<List<int>> y)

    If this is only being used for the names along the X axis, you could also just pass IEnumerable<string>, and use LINQ to convert the obejcts (via Select) to string...


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Proposed as answer by servy42 Thursday, February 23, 2012 6:29 PM
    • Marked as answer by MDMoura Thursday, February 23, 2012 6:31 PM
    Thursday, February 23, 2012 6:00 PM
  • I think I might use a few different constructors.

    It might be easier to use.

    Thank You Reed,

    Miguel

    Thursday, February 23, 2012 6:30 PM