In this tutorial you will learn the core of C# and its language essentials. This will allow you to write a simple C# program that you will then compile. The program will be a Visual Studio Form application
About this Tutorial
Objectives
Delegates will learn to develop applications using C# 4.5. After completing this course, delegates will be able to:
Use Visual Studio 2012 effectively
Create commercial C# Web Applications
Develop multi-threaded applications, Use WCF and LINQ
Audience
This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of C# will also find the content beneficial.
Prerequisites
No previous experience in C# programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.
Experience using a contemporary OO language such as C++ or C# would be useful but is not required.
Overview
In this tutorial we will be showing you the core features that are present in the C# programming language. This will range from variables and operators to using loops in programs, for the people who have had some programming experience the C# language is very similar to Java and in learning this you will be learning the key concepts of Java at the same time.
Estimated Time – 1 Hour
Not what you are looking? Try the next tutorial – Defining Types
Lab 1: Language Essentials
Lab 1: Language Essentials
Anatomy of a simple program -The most simple type of program in .NET is a console application.
Optionally declare an array of strings as input to Main().
Optionally return an int from Main().
namespace HelloWorldApp
{
class Program
{
static int Main(string[] args)
{
Console.WriteLine("Thanks for passing in {0} arguments!", args.Length);
return 0;
}
}
}
Variables
All programs use variables- you must initialize the variables before you use them.
type variableName = optional-initial-value; // Syntax int yearsToRetirement = 20; // Example
Constants – fixed variables, cannot be changed. Below is a table of keywords for variables consisting of their descriptions and ranges where each of them may be best suited to a specific purpose.
const type constantName = mandatory-compile-time-constant-value; // Syntax const double PI = 3.1415; // Example
Lab
Using the Console Class – Class permits simple console I/O.
Console.Write()
Console.WriteLine()
Console.ReadLine()
Use {0} etc. as placeholders in output string, you can use formatters to format output e.g.{0:c}. for {d8} it will be to 8 places and for {f4} it will have 4 places after the floating point.
String class represent a unicode character string – String literal have the format “xxx”; they are able to contain escape characters e.g. \n and to prevent the character expansion, prefix string literal with @.
Useful Properties/methods
Length.
Compare(), contains(), Equals(), Format() etc…
String objects are immutable – you can’t change them, if you need to change them use StringBuilder.
Arithmetic Operators – A symbol that takes an action
Basic Binary Operators – Takes 2 operands (% is the modulus symbol that returns a remainder e.g. 10 mod 3 = 1):
a + b
a – b
a * b
a / b
a % b
Basic unary operators – Takes one operand, the difference between a++ and ++a is when using the value for a++ it uses the value of a and then increments a afterwards; whereas for ++a it increments a and then uses its value:
+a
-a
a++
a–
–a
Conditional Operator – It is like an in-situ if test e.g. (condition) ? trueResult : falseResult. bool isMale; // boolean value either true or false
int age;
...
int togo = (isMale) ? (65 - age) : (60 - age); // if it is a man use 65 otherwise use 60
Console.WriteLine("You have {0} years to go to retirement.", togo);
For value types e.g. integers – Assign LHS variable a copy of RHS values. int a = 100;
int b = 200;
b = 42; // b is now 42.
a = b; // a is now 42.
For reference types e.g. classes – Assign LHS variable a reference to RHS object. Person p1 = new Person("John", "Developer", 25000);
Person p2;
p2 = p1; // p2 points to same Person object as p1.
Compound assignment operators – for a quick example a+=b means a = a + b and is just a quicker way of helping the programmer in creating an application:
a += b
a -= b
a *= b
a /= b
// Use *= compound operator:
x *= a + b;
// Equivalent to the following (note the precedence):
x = x * (a + b);
String Concatenation – you can conjoin string using the + operator but remember if you are using words to leave ” ” (spaces) between them. Strings can be seen as anything held in “” commas that can also have variables put between them e.g. “hello you are ” + age + ” years old”:
strResult = str1 + str2
strResult = str1 + obj
Using shortcut concatenation – str1 += str2.
String message = "Hello";
int a = 5;
int b = 6;
Console.WriteLine(message + a + b);
Console.WriteLine(message + (a + b));
Console.WriteLine("" + a + b);
Console.WriteLine(a + b);
Casting:
Implicit – Converts less-precise to more-precise e.g. byte > short > int.
Explicit – Conversions aka casting – (type) expression; might result in a loss of precision. int judge1Score;
int judge2Score;
int judge3Score;
...
double averageScore = (double) (judge1Score + judge2Score + judge3Score) / 3;
Relational Operators – 6 relational operators:
==
!=
>
>=
<
<=
Comparing Values
By using == or != on value types e.g. integers; you are comparing numeric types.
If you use == or != on reference-types objects; you are comparing object references, if you want to compare values use the Equals() method.
Logical Operators:
&& – Logical AND
|| – Logical OR
! – Logical NOT
Bitwise AND/OR/NOT and shift operators:
& – bitwise AND
^ – bitwise OR
| – bitwise inclusive OR
~ – bitwise NOT
<< – shift bits left
>> – shift bits right
Lab 3: Conditional Statements
Lab 3: Conditional Statements
Using if Tests:
Basic if tests, tests the condition and if it is true will run the code in the body. if (booleanTest) {
body
}
if-else tests, if it is true it will run the code in the body otherwise it will move to the else and run the code in the else body. This means we now have code for both true and false. if (booleanTest) {
body1
} else {
body2
}
if-else-if tests, this will test a condition and if it is true will do that code in the body otherwise it moves its way down the if statement to the next else if and tests that condition etc… if none of the conditions were true the else at the end will run its body code. if (booleanTest1) {
body1
}
else if (booleanTest2) {
body2
}
else if (test3) {
body3
}
...
else {
lastBody
}
Nesting if Tests, this is where you have an if statement inside an if statement and this can go on for many levels and without properly indented code can become very hard to understand. int age = ...;
String gender = ...;
if (age = 100) {
Console.WriteLine("centurion ");
}
if (gender == "Male") {
Console.WriteLine("man");
} else {
Console.WriteLine("woman");
}
}
Using switch Tests – switch statements is useful if you want to test a singleexpression against a finite set of expected values. switch (expression) {
case constant1:
branch1Statements;
break;
case constant2:
branch2Statements;
break;
...
default:
defaultBranchStatements;
break;
}
Lab 4: Loops
Lab 4: Loops
Using while loops:
The while loop is the most straightforward loop construct.
Boolean test is evaluated.
If true, loop body is executed.
Boolean test is re-evaluated.
Loop body will not be executed if test is false initially.
while (booleanTest) {
loopBody
}
Using do-while loops:
The do-while loop has its test at the end of the loop.
Loop body is always evaluated.
Handy for input validation.
Note the trailing semicolon.
do {
loopBody
} while (booleanTest);
Using for loops:
The for loop is the most explicit loop construct.
Initialization part can declare/initializevariables.
Test part can have as many tests as is needed.
Update part can do anything.
for (init; booleanTest; update) {
loopBody
}
Using foreach loops:
The foreach loop iterates through an array or collection.
Iterate through an array of integers – int[] examMarks = { 75, 85, 92, 71, 99 };
foreach (int m in examMarks)
{
Console.WriteLine("Mark: {0}", m);
}
Iterate through a collection of strings – List favouriteCities = new List();
...
foreach (string c in favouriteCities)
{
Console.WriteLine("City: {0}", c);
}
Unconditional jumps:
Sometimes it can be convenient to use unconditional jump statements within a loop.
If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Manage cookie consent
You can view this website without consenting to extra cookies. However you will need to accept the 'marketing' cookies to send messages via the contact forms & see any maps displayed on the site
Functional
Always active
Cookies necessary for the website to work.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.Cookies used to track user interaction on the site, which helps us to evaluate & improve the website.
Marketing: Forms & additional content (Marketing)
We need your permission to place ‘marketing’ cookies, so you are able to use the contact forms & see embedded content e.g. videos and maps. - - - - We have added protection to our contact forms to help prove that a human (rather than a spambot) is filling
If you would like to see more content like this in the future, please fill-in our quick survey.