Tech Off Thread

7 posts

What's the name of this (lacking?) C# language feature and why isn't it possible or is it?

Back to Forum: Tech Off
  • androidi

    Example:

    var list = new List<KeyValuePair<string, decimal>>();
    myClass.GenericMethod<typeof(list)>(list);

    I'm pretty sure C++11 had something like this, why doesn't C# have it?

  • androidi

    The problem I'm trying to solve is:

    I use a serialization lib which wants this:

    public static void Serialize<T>(Stream destination, T instance);

    and I want to call Serialize(stream, ????);

    Such that the ???? part is not manually typed in but inferred from the type of the list variable.

    How to do this?

  • androidi

    edit: looks like the workaround I had earlier has some issues

  • cheong

    How about adding this to the top of file:

    using listType = System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string, decimal>>; 

    And then change to the following?

    listType list = new listType();
    myClass.GenericMethod<listType>(list);

    Recent Achievement unlocked: Code Avenger Tier 4/6: You see dead program. A lot!
    Last modified
  • Sven Groot

    , androidi wrote

    Example:

    var list = new List<KeyValuePair<string, decimal>>();
    myClass.GenericMethod<typeof(list)>(list);

    I'm pretty sure C++11 had something like this, why doesn't C# have it?

    I'm not sure what's going on here. You can just use this:

    myClass.GenericMethod(list);

    The generic argument will be inferred from the type of list if not specified.

  • androidi

    @cheong: Thanks I hadn't thought of that.

    @Sven Groot:

    Yeah it does look like error on my part as I don't have a comment there explaining why I have made it more complicated that it should be. I'll get back to this if it starts to fail at runtime later.

  • Ion Todirel

    , androidi wrote

    Example:

    var list = new List<KeyValuePair<string, decimal>>();
    myClass.GenericMethod<typeof(list)>(list);

    I'm pretty sure C++11 had something like this, why doesn't C# have it?

    it's called decltype, and it's awesome, come back to the right side Wink

    C# doesn't have templates, so it wouldn't be that usefult there

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.