One of my main goals as I begin to learn C# is to seriously understand the language as best as possible, right from the start. This is something I’ve neglected to do previously in personal studies or courses I had back in school. I learned the languages fast, but would generally skip over any other information aside from this command is executed this way, none of the – beware when you use it this way and with this thing while it’s doing that thing over there.
First up: String, for all your wordiness
String is a variable type that allows you place a text value into the variable. Doing this will allow you to either manipulate or display the text.
A variable named myOtherString was declared as type string. The variable was then further defined with the value “Other”. When calling the WriteLine method, it will display the text “Other” onto the screen.
Batter up: Int, for Science!… err, Math!
Int is the variable type that allows you enter Integers and perform mathematical equations with them.
Smashing int and strings together, what happens?
So the next question that comes along – what happens when we try to add int and string into a variable of type string… what about into a variable of type int?
First – int + string into a string
C# is able to compensate for the fact that myFirstValue is an int when adding it to string it knows to convert the integer 1400 to a string of 1400.
Ok cool. So C# doesn’t freak out when you try to add an int and string into a string, what happens when you add them into an int?
When the variable that the sum is going into is of type int, a squiggly appears underneath the addition of the two values which says “Cannot implicitly convert type ‘string’ to ‘int'” and doesn’t allow you to run the program.
Double is the variable type that is used when a variable needs to hold a decimal number.
Next: Var, the type that’s not a type
(“But that isn’t in the title!”… yeah well the jingle doesn’t work with 4 parameters)
Var is a unique variable type in which it isn’t really a variable type. It’s container that can hold any type of variable, but once it’s been defined as a specific type (int, string, double) it must remain that type.The first two lines define and display myString. The 3rd line creates a new variable that holds the type of variable that myString is and then the 4th displays that type.