basic_c_sharp_cheat_sheet_learnappdevelopment.pdf

(77 KB) Pobierz
Basic C# Cheat Sheet
Basic Variables
Operators in C#
Type Conversion in C#
Comparing Stuff in C#
Loops in C#
Arrays in C#
Methods in C#
Classes in C#
Inheritance in C#
Exceptions in C#
2
3
5
6
7
8
9
10
12
13
1
Basic Variables
Variables are the smallest practical working blocks of any application. They are essentially small
pieces of data stored in special purpose containers.
Storing a number:
int myNum = 9;
(‘int’ stores a whole number)
(‘double’ stores a decimal number)
(‘float’ stores a decimal number - note the ‘f’ ending)
double myNum = 9.879;
float myNum = 10.876587f;
Storing words or letters
string myText = “I like this sheet”;
(‘string’ stores characters or sequences of them)
Variables are the basic building blocks of all software. They cannot be mixed so you cannot store
an int inside of a string or vice versa.
2
Operators in C#
Operators allow sums between numbers to take place. They also allow concatenation of strings
(adding words onto other words).
Adding a number:
int myNum = 9;
int otherNum = 10;
int result = myNum + otherNum;
(The result would be equal to 10)
Subtracting a number:
int myNum = 9;
int otherNum = 10;
int result = myNum - otherNum;
(The result would be equal to -1)
Multiplying a number:
int myNum = 9;
int otherNum = 10;
int result = myNum * otherNum;
(The result would be equal to 90)
Dividing a number:
int myNum = 9;
int otherNum = 10;
int result = myNum / otherNum;
(The result would be equal to 0). Wait what? Well, ‘int’ can only hold a whole number and 9 / 10
= 0.9. Therefore ‘int result’ simply drops the ‘.9’ part! Be careful when performing arithmetic!
3
Adding strings
string myText = “I like this sheet”;
string myOtherText = “Oh I really do!”;
string fullSentence = myText + “. “ + myOtherText;
(Result = “I like this sheet. Oh I really do!”;
4
Type Conversion in C#
You can’t mix types in C# but you can convert between them (with some limitations);
Convert from most types to string:
int myNum = 90;
string result = myNum.ToString();
(The result would be the word “90”)
Convert from string to number:
string myText = “98”;
int myNum = Convert.ToInt16 (myText);
(Result is number 98);
WATCH OUT! Following throws an app crashing error:
string myText = “Grant”;
int myNum = Convert.ToInt16 (myText);
BIG ERROR HERE!
Why an error? You cant convert a word to a number so your app will kick and scream, bringing
the whole thing down. Avoid type conversion where possible.
5
Zgłoś jeśli naruszono regulamin