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:


Neeraj Tripathi said...

A wormed Thanks 2 u.

Anonymous said...

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.


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

srego said...

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

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

Y-An said...

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.

Y-An said...

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#!

simi said...


First of all. Thanks very much for your useful post.

I just came across your blog and wanted to drop you a note telling you how impressed I was with the information you have posted here.

Please let me introduce you some info related to this post and I hope that it is useful for .Net community.

There is a good C# resource site, Have alook


Anonymous said...

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