Search code examples
c#collectionsemplace

Is there any C# analogue of C++11 emplace/emplace_back functions?


Starting in C++11, one can write something like

#include <vector>
#include <string>

struct S
{

    S(int x, const std::string& s)
        : x(x)
        , s(s)
    {
    }

    int x;
    std::string s;

};

// ...

std::vector<S> v;

// add new object to the vector v
// only parameters of added object's constructor are passed to the function
v.emplace_back(1, "t");

Is there any C# analogue of C++ functions like emplace or emplace_back for container classes (System.Collections.Generic.List)?

Update: In C# similar code might be written as list.EmplaceBack(1, "t"); instead of list.Add(new S(1, "t"));. It would be nice not to remember a class name and write new ClassName in such situations every time.


Solution

  • You can a bit improve @Boo variant with extenstion.
    You can create object instance with Activator.CreateInstance so it make solution more generic.

    public static class ListExtension
    {
        public static void Emplace<S>(this IList<S> list, params object[] parameters)
        {
            list.Add((S)Activator.CreateInstance(typeof(S), parameters));
        }
    }
    

    Note: not checked type and count parameters, so if you do something wrong, you get errors just in run-time