Data Types and Data Type Conversion | C#

Variables and Data Types

A Variable is like a bucket that we keep in the computers memory that we are can later retrieve. We create a bucket that is just the right size that we can hold and retrieve from.

Example:

// Strings are automatically set to an empty string when no value is set
string emptyStringVariable;

// Declare and initialize a variable with a value of type string
string firstName = "James";
string lastName = "Doe";

// Now that we have two variable, we can concatenate them and assign them to one variable of the same type. 
// We add an empty string in the middle in order to create some spacing.
string fullName = firstName + " " + lastName;

Whole Numbers

// Whole numbers are set to 0 when no value is set
int zeroValueVariable;

// from 0 to 255
byte myByte = 200;

// from 32,767 to -32,768
short myShort = 20123

// from 2,147,483,647 (billion) to -2,147,483,648
int myInt= 10230495;

// from 9 Quintillion to -9 quintillion
long myLong = 8560000000;

// float
float x = 3.5f;

// double
double y = 3d;

// decimal
decimal myMoney = 300.5m;

Data Type Conversion

When you are unable to assign a value to an variable because of the incorrect data type, you must explicitly convert it.

// long to int
long i = 20000000000;
int j = (int)i;

// Numbers to String:
int myInteger = 300;
string myString = myInteger.ToString();

// String to Numbers:
string myString = "100";
int myInteger = int.Parse(myString);

Arithmetic Operators

Math Operators + - * /

// Addition Assignment
int total = 3; // Assign 3 to the variable
total = total + 5; // Add 5 to the value of total
total += 5; // Add 5 again to the value of total

// Increment Operator:
int i = 10;
i++; //Equals 11

// Decrement Operator:
int i = 100;
i--; // Equals 99

Notes: Beware of order of precedence on arithmetic equation (use parenthesis). Beware of down casting (you will lose precision). Beware of overflow (use bigger types)

Advertisements

Leave a Reply