Learning C# Part 2: Language Fundamentals

Written By: Kevin Jordan

- 07 Jul 2006 -

Description: This series aims to take a beginning programmer to an intermediate level in C#. Topics covered in Part 2 include: C# program structure, declaring and intializing variables, characters, strings, constants, enumeration, converting between types, and expressions and operators.

  1. C# Program Structure
  2. Declaring and Using Different Variable Types
  3. Constants and Enumeration
  4. Converting Variables and Using Expressions
  5. Aww Man... Not Homework

Converting Between Types

Whenever you are performing operations on two different types, it may be necessary to convert it first. There are two different ways to handle the conversion, implicitly or explicitly. An implicit conversion is automatically performed for you by the CLR while explicit conversion requires you to ask the compiler to perform the action. Here's a list of implicit conversions supported within C#:

From To
sbyte short, int, long, float, double, decimal
byte short, ushort, int, uint, long, ulong, float, double, decimal
short int, long, float, double, decimal
ushort int, uint, long, ulong, float, double, decimal
int long, float, double, decimal
uint long, ulong, float, double, decimal
long, ulong float, double, decimal
float double
char ushort, int, uint, long, ulong, float, double, decimal

Here's how to perform an explicit conversion:

decimal d = 1234.56M;
int x = (int) d;

The type in parenthesis indicates what the value on the right side should be converted to. It is important to remember that explicit conversions can result in the loss of data. The sample above will lose the precision after the decimal giving us the value 1234 for x.

Expressions and Operators

Anytime you perform a mathematical calculation, assign a value, or compare two values you are creating an expression. An operator is the symbol that indicates what action you want to perform within you expressions, such as the + or = sign. Here are a few standard operations:

int x = 5; // assignment
x = 10 + 5; // mathematical plus gives us 15
x = 4 * 3; // mathematical multiplication gives us 12
x = 4 * (2 + 3); // the 2+3 is performed first giving us 24
x = 9 % 4; // this returns what is left over after dividing 9 by 4, in this case 1
 
// Here are some shortcuts
x++; // same as x = x + 1;
x--; // same as x = x – 1;
x += 5; // same as x = x + 5;
x -= 5; // same as x = x – 5;
x *= 5; // same as x = x * 5;
x /= 5; // same as x = x / 5; 

There are a lot more, but these are the major ones. There is also relational, equality, and conditional operators which are very important. Relational operators are the greater than, less than, and equal to statements. Equality simply tests for equality, and conditional operators are you and/or statements. We'll use these in the next section.

<< Previous

Next >>