As far as I know a string in C# is a reference type.
So in the following code ‘a’ should be equal to “Hi”, but it still keeps its value which is “Hello”. Why?
string a = "Hello";
string b = a;
b = "Hi";
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A number of the answers point out that strings are immutable; though that is true, it is completely irrelevant to your question.
What is more relevant is that you are misunderstanding how references work with respect to variables. A reference is not a reference to a variable. Think of a reference as a piece of string. You start with this:
Then you say that “b = a”, which means attach another piece of string to the same thing that
ais attached to:Then you say “now attach b to Hi”
You are thinking either that references work like this:
Then I say that
bis another name fora:Then I change
b, which changesa, because they are two names for the same thing:Or perhaps you are thinking that references work like this:
Then I say that
brefers toa:Then I change
b, which indirectly changesa:That is, you are expecting to make a reference to a variable, instead of a value. You can do that in C#, like this:
That means “for the duration of the call to M, x is another name for y”. A change to x changes y because they are the same variable. Notice that the type of the variable need not be a reference type.