How to Pass (from any index of) Array in function

In C++, I can do:


int array[]={0,1,2,3,4,5,6,7,8,9};

void PrintArray(int array[], int count)

{

for(int i=0; i<count; ++i)

cout<<array [ i ] <<endl;

}

void Main(void)

{

PrintArray(array, 3); //Print 0 1 2
PrintArray(&array[5], 3); //Print 4 5 6 *****How to do that*****
}


My Question is How can I Pass "&array[5]" in C#




Answer this question

How to Pass (from any index of) Array in function

  • Swanands

    C# tends to be more verbose than C++. It's annoying at first, but with intellisense it doesn't really make much different, and you end up gettind used to how things work. An example of something that's possible is:


    public static void Print<T>( IEnumerable<T> enumerable )
    {
    foreach (T t in enumerable)
    {
    Console.Write( t.ToString() );
    }

    Console.Write( "\n" );
    }

    public static IEnumerable<T> Split<T>(T[] array, int bound)
    {
    for (int i = 0; i < bound; i++) {
    yield return array[ i ];
    }
    }

    public static IEnumerable<T> Split<T>( T[] array, int begin, int end )
    {
    for (int i = begin; i < end; i++) {
    yield return array[ i ];
    }
    }

    static void Main( string[] args )
    {
    int[] array = new int[10];

    Print( array );
    Print( Split( array, 5 ) );
    Print( Split( array, 2, 7 ) );
    }



    The call site is simple and clean... Print can print anything that can be enumerated, and split can have as many overrides as you want. Of course this is more complicated than necessary, but it demonstrates yield return and generics, etc.

    Of course, this might not be as short as

    print(array+5, 10);

    but it's infinitely flexible, and isn't going to crash.

    Hope this helps a bit,
    Luke

    marco's right though. C# just takes some getting used to.

  • nimbusism

    At beginning it was difficult also for me change from c++ to C#. Many triks that I used in the past now I can't use anymore

    Anyhow, you have many possibiliy to solve this problem. For example, instead of passing to the method only the array and the counter you can pass it also the position from which start the printing..


  • krs_Karthick

    Thank for reply.

    I am now pass the "starting index" and "count" at the same function.



  • How to Pass (from any index of) Array in function