Working with variables and operators in C#

Simple Hello World! program

namespace TestHello
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine("Hello World!");
        }
    }
}

Output:
Hello World!
Press any key to continue . . .

Working with variables and operators

Naming variable: Start with lowercase letter. In a multiword identifier, start the second and each subsequent word with an uppercase letter. Eg: name, firstName.
Primitive data types: int, long, float, double, decimal, char, string, bool

Variable declaration and assignment and operations

int age; // declaring integer variable
age = 10; // assigning value integer variable
float floatVar = 0.42F;
double doubleVar = 0.42;
bool boolVar;

string a = floatVar.ToString(); // converting from float to sring
float b = float.Parse(a); // converting from string to float

/*In C#, the multiplicative operators (*, /, and %) have precedence over the additive operators (+ and –) */
2 + 3 * 4; // 14
(2+3)*4; // 20

/* The associativity of the operators determines how the expression is evaluated. The * and / operators are both left-associative */
4 / 2 * 6; // (4/2)*6=12

Associativity and the assignment operator

int myInt;
int myInt2;
myInt2 = myInt = 10; // The value assigned to the variable myInt2 is the value that was assigned to myInt.

int myInt, myInt2, myInt3 = 10; // Only myInt3 initializes with 10

Incrementing and decrementing variables

int x;
x = 42;
Console.WriteLine(x++); // x is now 43, 42 written out
x = 42;
Console.WriteLine(++x); // x is now 43, 43 written out

// infering the type of a variable from an expression
var myVariable = 99;
var myOtherVariable = "Hello"; 
var yetAnotherVariable; // compiler error
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s