1

I came across(inside(definition) of the string "class"(.NET)):

public String(char* value);

What is written in the commentary:

    // Parameters:
    //   value:
    //     A pointer to a null-terminated array of Unicode characters.

My questions:

Can I use it only in an unsafe context, does it still make sense to use that String(char* value) nowadays or is this just a relict from the past, based on this "ABC\0"(termination of that string) ?

If I can/should use it, how and what would be a situation for this method ?

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
user254197
  • 883
  • 2
  • 9
  • 31
  • @Nishant. I thought inside of e.g. "unsafe{ char c='G'; char * pc=&c; Console.Writeline(c);}" it looks more than c/c++ than c#, espeially the syntax reminds me of that. – user254197 Aug 14 '15 at 07:51
  • Pretty much a relic of the past, used to ease people from C++ code to C# code. I suppose it might be useful in some rare cases to do with P/Invoking unmanaged code and getting null-terminated strings back, but normally you'd be able to set thing up so the marshaller would handle that for you. – Matthew Watson Aug 14 '15 at 07:57
  • Note that it is C# `char`, so a unicode string... in C/C++ it would be `wchar_t`. If you want "8 bits strings" there is another group of constructors that accept `sbyte*` – xanatos Aug 14 '15 at 09:01

1 Answers1

1

Well, we have two possible scenarios:

  1. You don't need to work with unsafe code. If you don't need to work with unsafe code, don't use unsafe code. You will never use this string constructor.

  2. You need to work with unsafe code. If you need to work with unsafe code and char* for some reason¹, this method allows you to "convert" a char* to a standard .NET string after you are done with your unsafe operations.

¹ Possible use cases for unsafe code are outside the scope of this question.

Heinzi
  • 167,459
  • 57
  • 363
  • 519