You are on page 1of 30

C#.

NET Complete Training


Part-1 Basics:
Tip for learning PLs: Secret to learn programming is practice
Programming Languages
Low Level
• Difficult to learn

• Far from human language

• Fast in execution

• Hard to modify

• Hardware level

• Used to write hardware programs

• E.g., machine language and assembly

High Level
• Easier to learn

• Near to human language

• Slower in execution

• Easier to modify

• Not much facility at hardware level

• Used to write programs

• E.g., C++, C#, Python and Java

Examples of different Languages

Human languages English: How are you?

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
German: Wie geht’s dir?
High-level programming language Console.WriteLine("Hello, World!");
Low-level programming language mov eax,0
add edi,1

Machine language 0100100001101111011101110010000001100


0010111001001100101001000000111100101
1011110111010100111111
Examples of Equivalent Binary or Machine codes:

A 01000001 a 01100001
B 01000010 b 01100010

Compilers:
A compiler is computer software that transforms computer code written in one
programming language (the source language) into another computer language
(the target language). Compilers are a type of translator

The Compiler
Compiler:
• Compiled Languages: C++, C#, Swift, TypeScript
• Takes an entire program as input
• Executes faster
• Requires more memory
• Not cross-platform
Interpreter
E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
• Interpreted Languages: JavaScript, Python, PHP
• Takes a single line of code as input
• Executes slower
• Requires less memory
• Cross-platform

Visual Studio
An Integrated Development Environment (IDE) is a software application that
provides comprehensive facilities to computer programmers for software
development.

Features of VS:
1- Create new C# project Hello Word.
2- On write side there is solutions explorer containing all projects you have.
3- Solution is parent of all solutions you are creating.
4- Bold one is default one (we can change is set as startup project)
5- Explain IntelliSense

Types and Variables


Variables
Name given to a storage area that our programs can manipulate.

int x = 1;
string name = “Nauman”; (Statement termination)
Following are some most built-in Datatypes in C#

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
➔ Datatypes are very important
int (Keywords): used to store integer numbers (3 or 2000)
float: used to store floating point numbers (3.5 or 9.8)
double: used to store floating point numbers
decimal: used to store money values (2000$)
string: used to store text (“Ned” or “Vienna”)
bool: used to store true or false

var:
What if I don’t want to specify datatype of variable at the storage, what if I want
to leave it like it is and let it decide to assign type of data at the time of data
assignment.

1- Var in C# is strongly type once it declared it can only be of the


type with which it was initialized.
• var data type was introduced in C# 3.0. var is used to declare implicitly typed local
variable means it tells the compiler to figure out the type of the variable at
compilation time. A var variable must be initialized at the time of declaration.

What is .NET Framework?


Ans: We will come on it later on.

Lect-1: Namespaces in C#
Note: The namespace deceleration, using System, indicates that you are using the
System namespace.
Note: Console class is present in .NET Framework its used to write and read from
console.
Note: A Namespace can contain other namespaces
E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Note: Main method is the entry point of the class
Note: Anything we write in C# it will be in the class
What is Namespace?
A namespace is used to organize your code and is collection of classes, interfaces,
structs, enums and delegates.

Part -2
We will do following in this part:
• Dive deeper into C# data types
• Different error Types
• Take input from user
• Arithmetic operators
• Logical operators
• Comparison operators
• Conditional Statements (if and switch)

1- Datatypes in Details and at deep level


Following are C#.NET integer datatypes (These are built-in or
primitive datatypes)
E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Name .NET Type Size Range
sbyte System.SByte 1 byte -128 to 127
byte System.Byte 1 byte 0 to 255

short System.Int16 2 bytes -32,768 to 32,767

ushort System.UInt16 2 bytes 0 to 65,535

int System.Int32 4 bytes -2,147,483,648 to 2,147,483,647

uint System.UInt32 4 bytes 0 to 4,294,967,295

long System.Int64 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

ulong System.UInt64 8 bytes 0 to 18,446,744,073,709,551,615

Following are decimal datatypes in C#

Name .NET Type Size Precision Range


Float System.Single 4 bytes 7-digits 1.5 x 10-45 to 3.4 x 1038
double System.Double 8 bytes 15-16 digits 5.0 x 10-324 to 1.7 x 10308

decimal System.Decimal 16 bytes 28-29 digits 1.0 x 10-28 to 7.9 x 1028

DateTime: (All code based and you can see it in Lecturers with code files with all descriptions)

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Assignment 1:
Show following formats:
First format: 30-09-2018 09:09:59
Second format: Friday of month September year 2018
Third format:
Day Friday
Month September
Year 2018

Error Types in C#
Does error have types yes of course and we have to differentiate these errors to
solve them faster and efficiently a per nature of error.
following are some type of error in C#
1- Syntax Error
we have seen these in previous lecturers it’s like you are writing something
and C# doesn’t know it like you forget to type;
2- Runtime Errors Exceptions
when you have no Syntax errors and you have written 100% correct code
but when you run your program it still crashes. We have seen that in some
previous lecturers. In advance lecturers we will see how to handle these
exceptions.
3- Logical Errors

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
This error occurs when you are doing something wrong logically e.g.
performing some wrong calculation.

Naming conventions:
We will see here how to name your properties and objects

e.g. I Love Programming


Camel case: iLoveProgramming
Pascal or upper camel case: ILoveProgramming
Underscore or snake Case: i_love_programming
Kebab case: i-love-programming
e.g. First Name
Camel case: firstName
Pascal or upper camel case: FirstName
Underscore or snake Case: first_name
Kebab case: first-name

• Do choose easily readable identifier names. (HorizontalAlignment more English than


AlignmentHorizontal).
• Do favor readability over brevity. (GetProductCode is better than GetProCod).
• Avoid using identifiers that conflict with keywords of widely used programming languages e.g.
DateTime.
• Avoid using numbers and special symbols like? ~ -
E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Reading from Command Line:
namespace ReadLine
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("What is your name?");

string name = Console.ReadLine();

Console.WriteLine("Welcome " + name + ", welcome back!");


}
}
}

Arithmetic Operators:

Addition (+) ex. 1 + 1 = 2


Subtraction (-) ex. 3 - 1 = 2
Multiplication (*) ex. 2 * 2 = 4
Division (/) ex. 6 / 3 = 2 - quotient
E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Remainder (%) ex. 7 % 3 = 1 or 19 % 5 = 4
Remainder is the amount left over after division
19 / 5
19 cannot be divided exactly by 5
The closest you can get without going over is 3 x 5 = 15, which is 4 less than 19
So 4 is the remainder
• We will see if through practical example.

Precedence of Operators:
Solve it = 2+3*2-4+2
()
*/
+-
=
Conditional Statement (IF)
• We will see if through practical example. (please see code files from ECon)

Conditional Statement (Switch)


• We will see if through practical example. (please see code files from ECon)

Comparison Operators
E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
• We will see if through practical example. (please see code files from ECon)

Logical Operators
• We will see if through practical example. (please see code files from ECon)

More Logical Operators


• We will see if through practical example. (please see code files from ECon)

Even or Odd Example


• We will see if through practical example. (please see code files from ECon)
• Basic logic divide given number by 2 if result is 0 then its even number
otherwise its odd number.

Part-3
Advance Basics
We will learn following in this part:
• TryParse
• Constants
• String methods and manipulation
• Loops (for, While, and do while)
E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
• Math
• Random Numbers
• Arrays
Constants
• We will see if through practical example. (please see code files from ECon)

Command prompt:
• Let’s see it practically

String Manipulations
• Let’s see it practically. (please see code files from ECon)

Escape Sequences
• Let’s see it practically. (please see code files from ECon)

String Interpolations
• Let’s see it practically. (please see code files from ECon)

Loops
For Loop
• Let’s see it practically. (please see code files from ECon)

While and Do While loops


• Let’s see it practically. (please see code files from ECon)

Nested Loops + Loops exercise

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
• Let’s see it practically. (please see code files from ECon)

Math class
• Let’s see it practically. (please see code files from ECon)

Random Numbers
• Let’s see it practically. (please see code files from ECon)

Arrays
• Let’s see it practically. (please see code files from ECon)

Part-4
OOP (Object Oriented Programming) Part – 1
We will learn following in this part (Basic Concepts):
• Methods
• Classes
E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
• Inheritance
• Encapsulation
• Polymorphism
• Abstraction

Object Oriented Programming:


Object-Oriented Programming (OOP) refers to a type software design
programmers define data type of a data structure, but also the types of
operations (functions) that can be applied to the data structure.
In this way the data structure becomes an object that includes both
data and functions.

Class: A category of objects. The class defines all the common properties of
the different objects that belong to it.
Object: Refers to a particular instance of a class where the object can
be a combination of variables, functions, and data structures.
Method: A combination of instructions grouped together to achieve
some result. It may take arguments and return result.
Property: A member that provides a flexible mechanism to read, write,
or compute the value of a private field.

What is object-oriented programming?

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Vehicle(Class)
Wheeled vehicles (Sub Class) Non-wheeled vehicles
Four wheeled vehicle Two wheeled (Sub Class) vehicle Sea vehicle Air vehicles

Properties:
Color, Manufacturer, Max Speed, Carriage Capacity, Gasoline or Electricity
Methods
Start (), Stop (), Drive (), Refuel (), RunAtMaxSpeed (), TransportPeople ()
Objects
BMW X4
Ferrari Enzo
Kawasaki KX450F
Boeing 787 (etc.)

Four Pillars of OOP (Object Oriented Programming)


Inheritance: The process of creating the new class by extending the
existing class or the process of inheriting the features of base class is
called as inheritance.
Encapsulation: Encapsulation is a process of binding data members
(variables, properties) and methods together.

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Polymorphism: Poly means many and Morph means forms.
Polymorphism is the process in which an object or function take
different forms.
Abstraction: Abstraction is the process of showing only essential
features of an object to the outside world and hide the other
irrelevant information.

Methods Basics (Part-1) DRY (Don’t repeat yourself)


• A method is a code block that contains a series of statements. A
program causes the statements to be executed by calling the
method and specifying any required method arguments.
• Just write code in then form of method once and use it where
required.
Method Signature
Method name and its parameters types (but not the parameter
names) are part of the signature.
• Let’s see it practically. (please see code files from ECon (ProjectName:
OOPBasics)).

Methods Basics (Part-2 - Parameters and Return Types)


• Let’s see it practically. (please see code files from ECon (ProjectName:
MethodsParaAndReturnTypes)).

Methods Basics (Part-3 – Values Vs References)


• Let’s see it practically. (please see code files from ECon (ProjectName:
MethodsValVsRef)).

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Methods Basics (Part-4 – Methods OverLoading)
• You can have same method name but with different signature (already
explained above).
• Let’s see it practically. (please see code files from ECon (ProjectName:
MethodOverLoading)).
Methods Exercise (Please make Solution)
int a,b,c
double x,y,z
a+b
a+b+c
x+y
x+y+z
• Let’s see it practically. (please see code files from ECon (ProjectName:
MethodExe))

Foreach Loop:
A foreach loop is used to iterate through the items in a collection. For example,
foreach loop can be used with arrays or collections such as ArrayList, HashTable
and Generics. We will cover HashTable and Generics in later lecturers.
• It goes though the whole collection without changing anything in the body of
the loop (Advantage).

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Let’s see it practically. (please see code files from ECon (ProjectName:
ForEachLoop)).

Classes
What is class?
template or blueprint of the methods, variables and properties in a particular
kind of object.
So, for we have seen simple data types like int, float, double etc. If we want to
create complex custom types then we can make use of classes.
A class consists of data and behavior. Class data is represented by its fields and
behavior is represented by its methods.

What is Constructor?
• Constructors are called automatically when we will create instance of our
class. Constructors is basically used to initialize member of class.
• Constructors don’t have return values and always have the same name as
class.
• Constructors are not mandatory. If we will not provide constructor then
default parameter less is automatically provided.
• Constructors can be overloaded by the number and type of parameters and
they have same name as class and no return type.

Destructors
• Destructors have the same name as class with ~ symbol in front of them
• They don’t take any parameters and not return a value
• Destructors are places where you could put code to release any resources
your class was holding during its lifetime. (We will see it in details later).
E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Let’s see it practically. (please see code files from ECon (ProjectName:
InfoToClass and Classes)).
Static Methods
Let’s see it practically. (please see code files from ECon (ProjectName:
StaticMethods).
Inheritance
Inheritance provides reusability and this reduces the amount of code
and less amount of code is very easy to test. So, it could save lot of
time to write applications and also there is less probability of errors.
Note: We will specify all common fields, properties, methods in the
base, class which allows reusability. In derived classes we will only
have fields, properties and methods, that are specific to them.
1- C# supports only single class inheritance.
2- C# supports multiple interface inheritance.
3- Child class is a specialization of base class.
4- Based classes automatically instantiated before derived classes.
5- Parent class constructor executes before child class constructor.
Let’s see it practically. (please see code files from ECon (ProjectName:
Inheritance).

Encapsulation

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Encapsulation is a concept that binds together the data and methods
that manipulate the data, and that keeps both safe from outside
interference and misused.

Access Modifiers
Public: Access is not restricted.
Protected: Access is limited to the containing class or types derived
from the containing class.
Private: Access is limited to the containing type.
Internal: Access is limited to the current assembly.
Protected internal: Access is limited to the current assembly or types
derived from the containing class.
Let’s see it practically. (please see code files from ECon (ProjectName:
Encapsulation).

Polymorphism
Polymorphism enables/allow us to invoke derived class methods
using base class’s reference during runtime.
In the base class the method declared virtual, and in the derived class
we override the same method.
Polymorphism means having many forms. usually expressed as 'one
interface, multiple functions.
Static type or compile time (Overloading)
E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Dynamic type or runtime (Overriding)
Overriding: Allows you to change the functionality of a method in a
child class.
How and when to use keywords: virtual, override, new
derived from the containing class.
Let’s see it practically. (please see code files from ECon (ProjectName:
Polymorphism).
Abstraction

Abstraction: is a concept or an idea not associated with any specific


instance.
• You can not create instance of an Abstract class
Let’s see it practically. (please see code files from ECon (ProjectName:
Abstraction).

Cars Exercise OOPs Implementation:


Base class car
Child class Mercedes
Method DisplayInfo()
private decimal price;
public string color;
protected int maxSpeed;
E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Default values: price is 10000, and color is black and max speed is 300
Overridden values: price is 15000, and color is blue and max speed is
280.

Let’s see it practically. (please see code files from ECon (ProjectName:
CarsExerciseOOPImplementation).

Keyword: Region
• We use key word region to organize code
Let’s see it practically. (please see code files from ECon (ProjectName:
CarsExerciseOOPImplementation).

Topic: OPP Advance Level


We will learn following in this section
• More classes
• Namespaces
• Structs
• Enumerations
• This Keyword
• Interfaces

Topic: Sealed Class


Let’s see it practically. (please see code files from ECon (ProjectName:
SealedClasses).
E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Topic: Static Classes
• You can have only static members in these classes
• You cannot create instance of these classes
• That are sealed (Implicitly sealed)
Let’s see it practically. (please see code files from ECon (ProjectName:
StaticClasses).

Topic: Nested Classes


Let’s see it practically. (please see code files from ECon (ProjectName:
NestedClasses).

Topic: Partial Classes


Let’s see it practically. (please see code files from ECon (ProjectName:
Partiallasses).

Topic: Namespaces
Let’s see it practically. (please see code files from ECon (ProjectName:
NameSpaces).

Topic: Struct
Let’s see it practically. (please see code files from ECon (ProjectName: Structs).

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Classes VS Structs
Class:

✓ Declared with class keyword.

✓ Supports inheritance.

✓ User-defined constructors can be implemented.

✓ Data members can be initialized in the class definition.

✓ Reference type (Heap)


Struct:

✓ Declared with struct keyword.

✓ Doesn’t Support inheritance.

✓ User-defined constructors can’t be implemented.

✓ Data members can’t be initialized in the struct definition.

✓ Value type (Stack)


When to choose struct over class:
The majority of types in a framework should be classes, but if instances of the
type are small and commonly short-lived or are commonly embedded in other
objects define a struct.

Topic: Enumerations
Let’s see it practically. (please see code files from ECon (ProjectName:
Enumeration).
• Usually we use Enumerations to define Lists like list of week days,
months, cities etc.
• Each Enum item has constant integer value

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Countries Assignment:
Following will be structure of Country Class:
Child of a base class called world, and world class itself has couple of variables
called planet name and continent and properties to access these variables.
Variables : country name, capital, languages , currency
Properties : Country name, Capital, Languages and Currency
Constructor : initialize country name and capital
Methods : two overloaded methods to display welcome message
Struct: To define the first and second language for each country
Enums : 3 different enums for the continents, currencies and languages

Here is what is required


1. Define namespace called WorldNamespace.
2. Create a base class called World.
3. Create non-accessible (outside class) variable called planetName.
4. Define enumerations called Continents (with the continents names).
5. Create non-accessible (outside class) instance of enum Continents called
Continents.
6. Create a property to allow access to planetName and Continents.
7. Define two more enums called Currencies and Languages.
8. Define a child class called Country derived from World.

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
9. Define non-accessible (outside class) four variables in class Country which are
countryName, capital, countryLanguages and currency.
10. Define a struct called CountryLanguages which has two non-accessible
(outside class) variables called firstLanguage and secondLanguage and two
properties called FirstLanguage and SecondLanguage to allow access to
firstLanguage and secondLanguage.
11. Create four properties in class Country named CountryName, Capital,
CountryLanguages and Currencies to give access to four variables countryName,
capital, countryLanguages and currency.
12. Create a constructor to initialize properties CountryName and Capital.
13. Define two overloaded methods called SayHi (which says Hi) one with no
arguments and the other with one string arguments to mention the country.
14. In the main method create two instances of Country class name them
countryOneInstance and countryTwoInstance.
15. Create instance of the struct CountryLanguages called countryLanguages.
16. Assign two different languages using Languages enum.
17. Assign the instance countryLanguages to countryOneInstance.CountryLanguages.
18. Set planetName to “earth” and countryName to “any country”.
19. Set Currency and Continents to corresponding enums values.
20. Call SayHi methods and display values of countryOneInstance.

Topic: This keyword


Let’s see it practically. (please see code files from ECon (ProjectName:
ThisKeyword).

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Topic: Interfaces
An interface contains definitions for a group of related functionalities that a
class or a struct can implement.
• We create interface using interface keyword. Just like classes interfaces
also contains properties, methods, delegates or event but only
declarations and no implementations.
• It is compile time error to provide implementation for any interface
member.
• Interfaces can’t contain fields.
• If a class or a struct inherits from an interface, it must provide
implementation for all interface members. Otherwise we get a compiler
error.
• A class or a struct can inherit from more than one interfaces at the same
time, but whereas, a class can’t inherit from more than once at the same
time
• Interfaces are public by default and they don’t allow explicit access
modifiers.
• An Interface can inherit from another interface. A class that inherits this
interface must provide implementation for all interface members in the
entire interface inheritance chain.
• We can’t create instance of an Interface but an interface reference
variable can point to a derived class object.
• Interface naming convention is: Interface names are prefixed with capital
I.
• Think of it as contract that all the classes inheriting the interface should
follow.
• The interface defines the 'what' part of the contract and the deriving
classes define the 'how' part of the contract.
• Interfaces are public by default
E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
Let’s see it practically. (please see code files from ECon (ProjectName:
Interfaces).

Topic: Interfaces VS Abstract Classes


Similarities:
• Can't be instantiated directly
• Must implement all its members
• Can contain events, methods, and properties.

Differences:
Interfaces:
• Can’t have method implementations
• Allow multiple inheritance
• Can’t have access modifiers, everything is public
• Can’t contain variables
Abstract Classes:
• Can have method implementations
• Doesn’t allow multiple inheritance
• Can contain access modifiers
• Can contain variables

Topic: Exception
What is exception?
• An exception is a runtime error that happens during the execution of a
program.

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
• Exceptions provide a way to transfer control from one part of a program to
another.
Exception Handling:
• Exception handling is built upon these keywords: try, catch and finally
• Try: try block contains a block of code, exceptions are expected to happen if
we run it.
• Catch: program catches an exception with an exception handler at the place in
a program where you want to handle the problem.
• Finally: finally, block is used to execute a block of code, whether an exception
is thrown or not thrown.
We can use following try, catch block:
try
{
}
catch (SomeSpecificException ex)
{
}
We can use following try, catch and finally block:
try
{
}
catch (SomeSpecificException ex)
{
}
finally
E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman
{
}
Let’s see it practically. (please see code files from ECon (Projects:
ExceptionHandling and ExceptionExercise).

Topic: Composition

Topic: Delegate: Delegate is a Type Safe function pointer


Type-safe code accesses only the memory locations it is authorized to access. For example, type-safe
code cannot read values from another object's private fields. It accesses types only in well-defined,
allowable ways.

E-Consols
www.econsols.com /www.econsols.co.uk
Written By: Mr. Shahzada Nauman

You might also like