Tech Off Thread

7 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

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

Back to Forum: Tech Off
  • User profile image
    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?

  • User profile image
    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?

  • User profile image
    androidi

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

  • User profile image
    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
  • User profile image
    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.

  • User profile image
    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.

  • User profile image
    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

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.