Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointers in C#

Is this function declaration in C#:

void foo(string mystring)

the same as this one in C:

void foo(char *)

i.e. In C#, does the called function receive a pointer behind the scenes?

like image 518
Guy Avatar asked Nov 27 '22 04:11

Guy


2 Answers

In this specific instance, it is more like:

void foo(const char *);

.Net strings are immutable and passed by reference. However, in general C# receives a pointer or reference to an object behind the scenes.

like image 131
user7116 Avatar answered Dec 14 '22 11:12

user7116


There are pointers behind the scenes in C#, though they are more like C++'s smart pointers, so the raw pointers are encapsulated. A char* isn't really the same as System.String since a pointer to a char usually means the start of a character array, and a C# string is an object with a length field and a character array. The pointer points to the outer structure which points into something like a wchar_t array, so there's some indirection with a C# string and wider characters for Unicode support.

like image 38
Mark Cidade Avatar answered Dec 14 '22 10:12

Mark Cidade