Cast curiosity

  • Thread starter Thread starter WRH
  • Start date Start date
W

WRH

Hello
The following code snippet works fine...
....
string str = "";
ArrayList ac = new ArrayList();
char c = 'C';
ac.Add(c);

str += ac[0];
.....

However, if instead of str += ac[0] I use

str = ac[0];

the compiler complains...
"cannot implicitly convert type 'object' to 'string'
and I have to cast it to string, eg
str = (string)ac[0]

Its not a problem..just trying to understand...
 
WRH said:
the compiler complains...
"cannot implicitly convert type 'object' to 'string'
and I have to cast it to string, eg
str = (string)ac[0]

Its not a problem..just trying to understand...

When you use += it calls a static function which must have an overload for
char.

Michael
 
From ildasm, it looks like the function being called is the "string.Concat"
IL_0024: call string [mscorlib]System.String::Concat(object, object)


Michael C said:
WRH said:
the compiler complains...
"cannot implicitly convert type 'object' to 'string'
and I have to cast it to string, eg
str = (string)ac[0]

Its not a problem..just trying to understand...

When you use += it calls a static function which must have an overload for
char.

Michael
 
Rene said:
From ildasm, it looks like the function being called is the
"string.Concat"
IL_0024: call string [mscorlib]System.String::Concat(object, object)

Interesting. That means you can write code like this:

string x = "a";
x += this;

which probably isn't good because the programmer might have meant this.text
or something. It would probably be better if Concat just had a (string,
string) and a (string, char) overload. (and maybe some others for relevant
classes such as stringbuilder).

Michael
 
Thanks Rene & Michael C for prompt response
Interesting. That means you can write code like this:

string x = "a";
x += this;

Yes...we have eg...

string str = "";
double x = 12345.0;

str += x is the same as str += x.ToString() and
str += this is the same as str += this.ToString()


Michael C said:
Rene said:
From ildasm, it looks like the function being called is the
"string.Concat"
IL_0024: call string [mscorlib]System.String::Concat(object, object)

Interesting. That means you can write code like this:

string x = "a";
x += this;

which probably isn't good because the programmer might have meant
this.text or something. It would probably be better if Concat just had a
(string, string) and a (string, char) overload. (and maybe some others for
relevant classes such as stringbuilder).

Michael
 
Back
Top