Friday, December 14, 2007

Initialize char Array in C#

If you are used to initializing a char array in C++ like the following:


char mask[]={'a', 'b', 'c'};



There is a slight change when doing this in C#:

char[] mask=new char[] {'a', 'b', 'c'};


More examples:

http://www.java2s.com/Code/CSharp/Collections-Data-Structure/illustrateshowtoinitializearrays.htm

6 comments:

  1. Is there such thing as 2-dim char array in C#?

    For example,

    char[][] name ?

    If so, how do I initialize it?

    I tried

    char[][] name = new char[10][10];

    but it didn't work.

    Thanks.

    (The only reason I even try to use 2-dim char array is I need to pass something to a C function.)

    ReplyDelete
  2. Yes, the syntax is a little different from C++:

    char[,] name = new char[10,10];

    ReplyDelete
  3. Thank you...

    But I guess let me explain the problem I'm having..

    I need to pass a list of strings to a C function. And in C, in order to do that, I need a char[][]. How do I put a list of strings in C# to an array that C understands?? (C, not C++).

    In C#, for example,

    I can do listName[index].ToCharArray() for each string, but how do I put the entire list in a array so I can pass it to a C function?

    Please help. Thanks.

    ReplyDelete
  4. I tried this:

    char[][] name = new char[][] { new char[10], new char[20]};

    for (int i = 0; i < M_strListChosenColName.Count; i++)
    {
    name[i] = m_strListChosenColName[i].ToCharArray();
    }

    But when I tried to pass in "name", I got an error something about no marshaling support for nested array???

    Help please!! Totally new to C#!

    ReplyDelete
  5. var mask= new[] { 'a', 'b', 'c' };

    ReplyDelete

Note: Only a member of this blog may post a comment.