I read String* in C++ code and got confused, is there any necessarity to use String* ? Can I use char* instead? E.g. StreamReader has ReadLine() function, why not require user arrange a char array first and the function justs stores the string in it, returns a char* pointer and everything works just fine.
3 Answers
Notice that char* is a pointer to single string or multiple characters (array of chars), while string* is a pointer to a single or mulitple (array) of string objects. However, C# doesn't support pointers to managed types (such as string)
Examples:
unsafe void f() { char ch = '3'; char* cPtr = &ch; *cPtr = '4'; // ch == '4' fixed (char* ccPtr = new char[30]) { *(ccPtr + 15) = '4'; // arr[15] == '4' } string* ptr; // error: cannot declare a pointer to managed type fixed (char* pptr = new string(new char[] { 'a', 'b', 'c' })) { pptr[2] = 'd'; } } 2 Comments
In C# strings are generally handled by the C# type string or the .net type String (which is the same thing). char* is the C/C++ way of thinking of strings. While pointers do exist in C# they really aren't the way to go (they are officially unsafe). A character array will be a char[], not a char*.
In C# class instances are stored as references and structs as values. A reference is basically the managed version of a pointer. If you pass a class instance you are passing the object by reference, if you pass a struct you are passing by value. In other words, where you want data that you would pass as a pointer to a class/struct in C++ you should use a C# class. The advantages are that you pass by reference and that you can use it do the kinds of things you could do with a pointer (like linked lists). The disadvantage is that if you put a class inside a class you increase the number of redirections (and therefore the access time). Where you would want to store the data as values (for instance to reduce the number of indirections for a struct inside a class) you should use a struct. The advantages and disadvantages are the opposite of a struct with the exception that you can still pass a struct by reference by using the in/ref parameters.