String question

  • Thread starter Thread starter Tdw
  • Start date Start date
T

Tdw

In C#, you can use the string data type to hold a series of characters. The
string can be compared to another string using the == operator in the same
way that you compare numeric or character variables. However, you can only
use the == comparison operator with strings that are assigned literal
values; you cannot use it with strings that are created through several
other methods. Why?
 
Tdw said:
In C#, you can use the string data type to hold a series of characters. The
string can be compared to another string using the == operator in the same
way that you compare numeric or character variables. However, you can only
use the == comparison operator with strings that are assigned literal
values; you cannot use it with strings that are created through several
other methods. Why?

That's incorrect -- where did you hear that?

If that were true, the following wouldn't work:

static void Main(string[] args)
{
int i = 100;
string a = i.ToString();
string b = a;

Console.WriteLine(a == b);
Console.ReadLine();
}

There are no string literals in that code.
 
It came from a question in a class I am taking. I could not understand it.
C# Learner said:
Tdw said:
In C#, you can use the string data type to hold a series of characters. The
string can be compared to another string using the == operator in the same
way that you compare numeric or character variables. However, you can only
use the == comparison operator with strings that are assigned literal
values; you cannot use it with strings that are created through several
other methods. Why?

That's incorrect -- where did you hear that?

If that were true, the following wouldn't work:

static void Main(string[] args)
{
int i = 100;
string a = i.ToString();
string b = a;

Console.WriteLine(a == b);
Console.ReadLine();
}

There are no string literals in that code.
 
Tdw said:
In C#, you can use the string data type to hold a series of characters. The
string can be compared to another string using the == operator in the same
way that you compare numeric or character variables. However, you can only
use the == comparison operator with strings that are assigned literal
values; you cannot use it with strings that are created through several
other methods. Why?

That's not true, because the == operator is overloaded for strings in
..NET. However, you need to be very careful, because operators are not
applied polymorphically, so:

string s1 = new string(new char[]{'a','b'});
string s2 = new string(new char[]{'a','b'});

object o1=s1;
object o2=s2;

s1==s2; // True
o1==o2; // False - it's using reference identity

If you use .Equals in both cases, they'll both be true.
 
Back
Top