Question with coding

Soli
by Soli · 3 posts
6 years ago in .Net (C#, VB, etc)
Posted 6 years ago · Author
Hello :excitedwave:

I'm tinkering with some C# tutorials and trying to figure out this code. I modified the tutorial code because I just wanted to play around with it and see what happened if I changed things around. I'm having lots of fun and loving how things change; however, I'm confused as to why I need to add the work "string" in one section and not the other when the string looks identical.

Code
 string aFriend = "Bill";
Console.WriteLine("Hello " + aFriend);
aFriend = "Maira";
Console.WriteLine($"Hello {aFriend}");
string firstFriend = "Maria";
string secondFriend = "Sage";
string enemy = "Bill";
Console.WriteLine($"My friends are {firstFriend} and {secondFriend} but not {enemy}");


Why do I need
Code
string aFriend = "Bill";

vs
Code
aFriend = "Maira";


I took "string" out of the code and I got an error. I only took it out of the first line.
Thank u guys and I hope someone out there can clarify for me. I can't just accept that it has to be this way just because. I need to know the reason or I'll obsess over it. :awesome4:

Edit: I'm aware that
Code
Console.WriteLine("Hello " + aFriend);
and
Code
Console.WriteLine($"Hello {aFriend}");
give me the same results. I just wanted to keep the two different codes in here for reference so I remember to look at "string concatenation" in my notes.
Posted 6 years ago
~Moved to Programming & Scripting > .Net~

The first line:

Code
string aFriend = "Bill";


Is declaring a string called "aFriend" and giving it a value. Since you've already declared it, you no longer need the type identifier. The next line:

Code
aFriend = "Maira";


Is simply changing the value of the string "aFriend" that you declared previously.


TL;DR:

The first line tells the program to create a new string string called "aFriend" the second line is just changing the value of "aFriend".
Posted 6 years ago · Author
Ty very much. That makes a lot of sense now.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Sign in

Already have an account? Sign in here

SIGN IN NOW

Create an account

Sign up for a new account in our community. It's easy!

REGISTER A NEW ACCOUNT