Wednesday, June 4, 2014

Variables and Data Types

Variables in C# (and other object oriented languages) need to be defined and then initialized (brought to life / created!). The general format for the action of defining a variable is the following:

NOTE the semi-colon (;) at the end of these statements! This semi-colon is known as a line terminator, and its purpose is to tell the compiler the specific "line" or segment of code is completed. It can be useful if you wanted to break one segment of code (one action) into multiple lines to make it easier to logically read/understand, but to the compiler it is simply one code.

Data type can be filled in with any valid C# data type. Here is a summary of the main ones below. In addition, you can also make a user-defined data type. Another option is that the variable list can have multiple types that are separated with a comma.

int (integer) has the same definition here as it would in math! And integer will store whole numbers without decimals. is short for integer, a data type for storing numbers without decimals. This is the most common type for using numbers! It will store positive and negative whole numbers inclusive from [-2147483648 to 2147483647] because it is 32-bit (meaning it is equal to 2^32).. let me know when it goes above that (if ever!).. although as a chemist I know quite a few variables larger than int would not be able to handle..

long is a bigger version of int and rarely utilized. This is 64-bit and hence, 2^64. Your range of numbers here would be -9223372036854775808 to 9223372036854775807.

decimal is a 128-bit data type that is commonly used when representing: $$$.

string is used for storing multiple characters (random characters, a word, a phrase, or a name). In C#, strings are immutable, AKA not able to be changed. So, if a method changes a string.. what it really does is return a new string.

char is for storing one single character.

bool is has 2 vales: true and false. This is great for logical if/then type of statements.

float is for storing data that may/may not have decimals. It has less precision and a larger range than decimal (the $$$ one) and is usually used for other sets of decimal numbers like in arithmetic type of calculations.

So, do you remember this?

How to actually define a variable:

If you want to do multiple variables:

You could write it this way too (they are equivalent!):

You assign an initial value by using this general formula:

How to actually initialize a variable :

Here is a larger example that puts the concepts all together (literally adding them):

Using this, you will get the following output

So the general basic rule for adding in data types is to follow this: