Working with Variables, Operators, and Expressions in Microsoft Visual C#

  • 12/15/2012

Chapter 2 Quick Reference

To

Do this

Declare a variable

Write the name of the data type, followed by the name of the variable, followed by a semicolon. For example:

int outcome;

Declare a variable and give it an initial value

Write the name of the data type, followed by the name of the variable, followed by the assignment operator and the initial value. Finish with a semicolon. For example:

int outcome = 99;

Change the value of a variable

Write the name of the variable on the left, followed by the assignment operator, followed by the expression calculating the new value, followed by a semicolon. For example:

outcome = 42;

Generate a string representation of the value in a variable

Call the ToString method of the variable. For example:

int intVar = 42;
string stringVar = intVar.ToString();

Convert a string to an int

Call the System.Int32.Parse method. For example:

string stringVar = "42";
int intVar = System.Int32.Parse(stringVar);

Override the precedence of an operator

Use parentheses in the expression to force the order of evaluation. For example:

(3 + 4) * 5

Assign the same value to several variables

Use an assignment statement that lists all the variables. For example:

myInt4 = myInt3 = myInt2 = myInt = 10;

Increment or decrement a variable

Use the ++ or -- operator. For example:

count++;