Search code examples
c#c++functioniteratorenumerator

C++ to C# conversion


I am new to C#, I am doing my practice, by converting some code in C++ to C#. But stuck here, don't know how to convert this function to C#, which take any collection, its 1st element and its last element and add an element in it.

    template<class _Col>
void __insert
    (
    _Col&                   collection,
    typename _Col::iterator first,
    typename _Col::iterator last
    )
{
    for ( ; first != last; ++first )
    {
        collection.insert( *first );
    }
}

Solution

  • Let me try to explain:

    1. It is a generic function.
    2. It use come sort of collection. with iterators in our case IList<Type> interface for collection from System.Collections.Generic namespace.

    so lets get started:

    as I know C# default containers did not provide iterator feature so I resplaced it by usage IList<Type> interface wich provide similar to iterator indices.

    As you can see it is not good to do like this

    template<class _Col>
    void __insert
        (
        _Col&                   collection,
        typename _Col::iterator first,
        typename _Col::iterator last
        )
    {
        for ( ; first != last; ++first )
        {
            collection.insert( *first );
        }
    }
    

    Because _Col can contain not only template collection classes but also any other class, and if this other class will not prowide proper interface the compilation process fails. The same is for iterators there are many types of it.

    So I strongly suggest you to stick convention, that if you consider to use the template type as some sort of collection in function, try to use collection<Type> declaration on parameter, and funcName<Type> on function. That will ensure you to process your data in proper way.

    static void Insert<Type>(IList<Type> outputCollection, IList<Type> inputCollection,  int start, int end)
    {
          if (end >= inputCollection.Count)
             return;
    
          for (int i = start; i < end; i++)
              outputCollection.Add(inputCollection[i]);
    }