why can't create a string pointer in unsafe code?

  • Thread starter Thread starter fairyvoice
  • Start date Start date
F

fairyvoice

Hi, I want to ask some basic question about the string type. When compiling
the unsafe code:
---------
string a = "wori";
string* b = &a;
---------
it pops up errors saying both 'string*b' and '&a' are illegal because string
is a managed type, while in the same case the 'int' type is available.
Why can't i get the point or the address of a string type? Is that because
string is immutable and every time you change it a new address will be given?
Thx in advanced
 
fairyvoice said:
Hi, I want to ask some basic question about the string type. When
compiling
the unsafe code:
---------
string a = "wori";
string* b = &a;
---------
it pops up errors saying both 'string*b' and '&a' are illegal because
string
is a managed type, while in the same case the 'int' type is available.
Why can't i get the point or the address of a string type? Is that because
string is immutable and every time you change it a new address will be
given?
Thx in advanced

I believe it is because managed types can be moved in memory by the garbage
collector so a pointer is not always going to remain valid. What are you
trying to do?

Michael
 
Thank you Michael and Rossum.
And Michael, you say it is because of the garbage collection, then most
type in .net are managed type and garbage collection will deal with all of
them, then why only string is illegal to get a pointer?

and Rossum, i know i can change the value in this way now, but i still want
to know why i can not get a pointer to the string type, thanks.
 
fairyvoice said:
And Michael, you say it is because of the garbage collection, then most
type in .net are managed type and garbage collection will deal with all of
them, then why only string is illegal to get a pointer?

The key is that there are two different kinds of "types" in C#: value
types, and reference types. The types that hold ordinals (byte, char,
bool, short, int, long, etc.) and the floating types (float, double) are
value types. You can get a pointer to those. Object and string are
reference types. You can't get a pointer to those.
and Rossum, i know i can change the value in this way now, but i still want
to know why i can not get a pointer to the string type, thanks.

Basically, because that's just not how C# works. C# is not C++; you need
to think about the problem differently.

I assume you are trying to use the pointer for efficiency, but it's a false
economy. Remember that copying a string variable doesn't actually copy the
string:

string s = "Testing";
string t = s;

There's only one string there, with two references to it.
 
Back
Top