Learn C# in 72 Hours

for Beginners

An Advanced Guide with a beginner’s Approach. (coupled WITH EXAMPLES IN PICTURES)

Authors

Emmanuel Clem-Akins jr

Thank you for buying this book

Learning with our approach will be of great help for you, because we have carefully explained every necessary information you need concerning C# Language in the book. Irrespective of your previous knowledge in C#, this book will be of a great tool for you.

Make sure you Read

Have you thought of having a copy of the printed version? Do you know having the printed version will allow you to learn fast?

Therefor Have made the kindle version free for you, in order for you to purchase the paperback- this enable you to have the kindle and printed versions.

Get the paperback of this book for just $9.99

Click the link

https://www.amazon.com/dp/B08BDZ5Q31

Thank you once again

Be the first to receive update on my next books contact me directly

Clementsemmanuel1@gmail.com

Contents

C# INTRODUCTION

What is C#?

Usage of C#

The Importance of C#

C# Get Started

C# IDE

C# Install

C# Syntax

C# Comment

C# Multi-line Comments

C# Variables

Declaring or creating variables

Constants

Display Variables

Declare Many Variables

C# Identifiers

C# Data Types

C# Type Casting

C# User Input

C# Operators

Arithmetic operators

C# Assignments Operators

C# Logical Operators

C# Math

C# Strings

String length

String concatenation

String interpolation

Access strings

Special character

Adding numbers and strings

C# Booleans

Boolean values

Boolean Expression

C# If...Else

C# conditions and if statements

The if Statement

The else statement

The else if statement

Short Hand if….Else (Ternary Operator)

C# Switch

The Break Keyword

The default Keyword

C# While Loop

The Do/While Loop

C# for Loop

The foreach loop

C# Break and Continue

C# Break

C# Continue

Break and continue in While Loop

C# Arrays

Access the elements of an array

Change and array elements

Array Length

Loop through an array

The foreach Loop

Sort Arrays

System.Linq Namespace

C# Method

Create a method

Call a method

C# Method Parameters

Parameters and Arguments

Default parameter value

Multiple parameters

Return Values

Named Arguments

C# Method Overloading

Method Overloading

C# OOP

C#- What is OOP

Advantages of object-oriented programming

C#- What are Classes and Objects

C# Classes and Objects

Classes and Objects

C# Class Members

Class Members

C# Constructors

Constructor Parameters

Constructors Saves time

C# Access Modifies

Private modifier

Public modifier

Access Modifies?

C# Properties (Get and Set)

Properties and Encapsulation

Properties

Automatic Properties (Short Hand)

Encapsulation

C# Inheritance

Inheritance (Base and Derived Class)

The sealed keyword

C# Polymorphism

C# Abstraction

Abstract Classes and Methods

C# Interface

Notes on interfaces

When to use interface and why we use them.

Multiple interfaces

C# Enum

Enum inside a class

Enum value

Enum in a switch statement

C# Files

Working with files

Write to a file and read it

C# Exception

Finally

The Throw keyword

C# How to add two numbers

Add two numbers

Copyright © 2020 by Emmanuel Clem-Akins jr

All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or other electronic or mechanical methods, without the prior written permission of the Author.

Thank you for buying this book

Leaning with our approach will be of great help for you, because we have carefully explained every necessary information you need concerning C# Language in the book. Irrespective of your previous knowledge in C#, this book will be of a great tool for you.

Powerful Offers you shouldn’t miss

Our Next Books In this series

JavaScript for Beginners

An Advanced Guide with a beginner’s Approach. (Code Fast with Simplicity Series Book 2)

Html for Beginners

An Advanced Guide with a beginner’s Approach. (Code Fast with Simplicity Series Book 3)

CSS for Beginners

An Advanced Guide with a beginner’s Approach. (Code Fast with Simplicity Series Book 4)

MySQL for Beginners

An Advanced Guide with a beginner’s Approach. (Code Fast with Simplicity Series Book 5)

jQuery for Beginners

An Advanced Guide with a beginner’s Approach. (Code Fast with Simplicity Series Book 6)

Note- All this books Paperback will be sold less than $15...Make sure you get your own printed Copies

Giant Bonus

The combined manuscript

Learning Web design with C#, html, JavaScript, CSS and jQuery

An Advanced Guide with a beginner’s Approach. (Code Fast with Simplicit y

C# INTRODUCTION

C# Introduction

What is C#?

C# programmer language is designed and created by Microsoft with runs on the .NET framework. Practically the programming language is similar to other language such as Java and C++. it was first release in 2002, but the current and latest version, which is c# 8 was released in 2019. an object-oriented programming language which is normally pronounce as “C-sharp” [C#] has its roots from the C Family [C++, C#, and so on].

Usage of C#

Desktop applications

Database applications

Web services

VR

Mobile applications

Games

Web applications

Web sites

And much more

The Importance of C#

This web programming language is very essential and one of the most popular language

C# is very easy to understand, and anyone can learn it

C# have similar comparison with programming language such as java and C++, which gives programmers the ability to switch between the programming language.

In C# codes can be reused by programmers, which aids lowing developments expenses.

C# provides a clear structure to programs.

C# Get Started

C# Get Started

C# IDE

Integrated development environment [IDE] is designed to compile and edit code which makes it the perfect way to start using C#. You can as well make use of Visual studio community [you can check for the link in the book index section]

Due to experience and as a beginner, it is advisable to make use of Visual studio community rather than Integrated development environment [IDE] due to the fact that all application written in C# makes use of .NET Framework and given that the language, framework, and the program are designed by Microsoft, using Visual Studio will be more preferable.

C# Install

After you must have download and installed the visual studio installer, select .NET workload, then select the button [Modify/Install button].

After you have concluded the installation, Select the Launch button to use the visual studio. Create a project by clicking on [Create a new project] to get started.

Move on to select install more tools and features” button. From the list of option select ‘Console App (.NET core)” and tap on the Next button:

Whatever name you want, insert or type in a name, and tap on the create button. After you have set up a name for your project Visual studio will generate some code for you to get started

You will comprehend the code later, for now you are to focus on running the program

C# Syntax

C# Syntax

We produced a C# file called Program.cs previously, the subsequent code was used to print "Hello World"

Program.cs

Explanation

Like I said earlier explaining the code will be vital and important, so please concentrate in order for you to understand each lines of code, as this will be vital and important for your programming journey in C#.

Line 1

Using system: this tells us we are able to use classes from the system namespace.

Line 2

In C#, white space is ignored totally, on the other hand, the code is more understandable using multiple lines.

Line 2

Namespace:

Namespace- this is perfect for organizing your code i.e., it helps you to organize your code, and an also container for classes.

Line 4

Curly braces {} -this helps to identify the starting and ending of a block of code, when coding.

Line 5

Class- it provides functionality to your program, and it's a container for methods and data. Always keep in mind that line of code that runs in C# should always be in a class.

Practically, beginners always have issues in understanding how to use namespace, class, and using system as well as how they function. but all you have to do at this stage is to always keep in mind, is the functionalities as we move in a chapter, we'll talk more about them.

Line 7

Also, when it comes to C# program, one of the things that normally appear is the main method, because any code that is found in a curly bracket {} are always executed. Understanding the keywords after and before main at this stage should not bother you because, as we move on in the next chapter will explain more of it.

Line 9

Console- this has a writeLine() method which helps to output or print a text. It is a class of the system namespace.

Whenever you skip over the use of using system line, a writeLine() must be used to print or output a text. i.e. system.console.writeline() should be written to output or prints text.

Keep in mind - a semicolon (:) is used to end a c# statements.

Keep in mind - C# are case sensitive i.e. "Using System" is different from "using system"

Note - filename in C# does not have to be alike or match the class name, but in most cases, it appears that way for a more clarified organization.

In order for you to save a file you have to save it properly and by adding .cs when ending the file name.

WriteLine or write

WriteLine() is one of the most common way two outputs a text or anything in C#, write() can as well be used.

But there is practical difference between them, in writeLine () print output on a new line. Write () output on the same line. Just keep in mind that for a better clarified statement or text you need to ask space where needed.

Result:

Good morning!

Good morning! The same line.

C# Comment

C# Comment

Explaining code in c# can be achieved by using comments and it also helps it to be more readable for its users. Comment can also the used to test alternative codes before execution.

C# automatically ignore text between //an end of the line that is any text within that range will never be executed by C#

Comments with single line (i.e. single-line comments) begins with (//) forward slashes

Illustration

A single-line comment at the end of a line of code is used in the illustration below:

illustration

C# Multi-line Comments

Comments with multi-line can be Identify through these symbols /* and */. every multi line comments begins with /* and end with */. C# will automatically overlook any text written in between the symbols (/* and */)

Illustration below makes uses of multi-line comments for explaining code.

Illustration:

In a nutshell, the use of comments in your coding depends on your preference, but in C# programming world, (multi-line comment) are used for longer comments, while (single line) are used for shorter comments.

End Result:

Good morning!

Good morning! The same line.

C# Variables

C# Variables

Variable are used for storing data values in C#, and container used in keeping/storing data. Also, variable have different types which are defined by keywords. Below is the different variable you need to know.

double - This type of variable is used to keep floating point numbers that has decimal for example 10.16 or -22.98

string - This type of variable is used to store text "Good morning". Whenever you see a value surrounded by double quotes then, this tells you it is a string value.

int - This type of variable is used to store integers i.e. whole number. For instance, 125 or -9

char -This type of variable is used to store or keep a single character take for instance a or 'C'. Whenever you see a value surrounded by a single quote this tells you it is a char value.

bool - this is a type of variable that stores or Keep values that has two States. For instance, true or false

Declaring or creating variables

Whenever you want to create a variable, you have to specify the type and must be assigned to a value.

Syntax

Type variableName = value;

C# type is a type (such as int or string), and the name of the variable is variableName (such as name or x). And the function of the equal sign is to assign values to the variable.

If you want to create a variable that will store number, follow the instructions below:

Example

You will first have to create a variable that is called (myNum)  of type int  then move on to assign it the value 20 :

A variable can be declared without assigning the value, moreover assign the value afterward:

Keep in mind that whenever you assign a fresh value to an existing variable, the previous value will overwrite automatically:

Constants

Constants keyword (const) is use to avoid overwriting existing values, its can be added to keep the existing value safe from overwriting, by adding the const keyword you are declaring the variable as constant, which implies read-only and unalterable).

You can store the same value using (const) keyword, this is done to stop other from messing your code, a variable will store the same value when the const keyword is been used.

Example of a constant, which is PI (2.14159). Keep in mind- before you can declare a constant variable, the value must be assigned, if not you will encounter an error, a value is required by a const field.

Other Types

Demonstration of Declaration of other types variables are showed below:

Display Variables

To display variable values to the console window. WriteLine()  method is frequently used

Text and variable are merge with the + character

Illustration

Two variables can be added together with the + character

Based on the above illustration, below are the results to expect;

x stores the value 8

y stores the value 5

Display the value of x + y, which is 12 , Let make use of WriteLine()  method.

Declare Many Variables

Comma is use to declare more than one variable, of the same type. A comma-separated list can be used.

C# Identifiers

C# Identifiers

Unique names are given to C# variables for it to be identify properly, examples of identifiers are (e.g x and y) or totalVolume, sum etc)

Keep in mind that using a more descriptive names is important for you to understand and maintain code.

in constructing names for variables. there are general rules you must follow:

Names must/contain:

Letters, digits and the underscore character (_).

Begin with a letter.

Start with a lowercase letter and should not contain whitespace

They are case sensitive take for instance "myVar" and "myvar" are not the same variables.

C# Data Types

C# Data Types

Remember a variable in C# needed be a precise data type, like we talked about it in the previous chapter:

Numbers

They are divided into two groups

Floating-Point Types

These numbers have a fractional part that contains one or more decimal. Float and double are valid types.

Despite the fact that we have many types in c#, the int which is for whole number and double which is for floating point num) are the most used or frequently used for numbers. But as you read on everything will be explained to you explicitly during the course of the book.

Integer Types

This type of data type can store positive or negative numbers and whole number as well without decimal, int and long added value types.

Int-

This type of data type can store all numbers ranging from -2147482648 to 2147482647.

Illustration

Long

This type of data type can keep whole numbers ranging from -9222272026854775808 to m, keep in mind that the value must be ended with "L":

Illustration

Floating Point Types

Whenever you are in need of a number with a decimal, floating-point types is what you should use.

Float

This data type can keep fractional numbers ranging from 2.4e- 028 to 2.4e+028. Keep in mind that "F" is needed to end the value.

Illustration

Double

This type can keep fractional numbers ranging from 1.7e - 208 to 1.7e+208.

Keep in mind that "D” is needed to win the value.

Illustration

Use double or float?

When it comes to the precision of the floating-point value, this helps to indicate or display the number of digits the values can have right after the decimal point. Only six or seven decimal digits is obtained by the precision of float, while the precision of double variables have about 15 digits so it is advisable to use double variables for calculations.

Scientific numbers

In the case of a scientific number, a floating-point can also has a scientific number with an “e" to show the power of 10:

Booleans

bool keyword is used to declare a Boolean data type. And it can only accept the value true or false.

Illustration:

And in most cases, they are used for conditional testing.

Characters (char data type)

These data type is used to store or keep a single character and these characters are surrounded by single quotes. ‘B’ or ‘d ‘

Illustration

Strings

This data type is frequently used to store sequence of characters that is text and their values are to be surrounded by double quotes.

Illustration

C# Type Casting

C# Type Casting

When we talk about type casting in c# this is when a value of one data type is being assigned to another data type.

There are two types of casting in C#

Explicit casting

Implicit casting

Explicit casting- This manually convert larger type to a smaller type size.

Double->float->long->int->char

Implicit casting- this automatically converts smaller type to a bigger size.

Char->int->long->float->double

Implicit casting

This is when you convert smaller size type to a bigger size type, it is normally done automatically.

Explicit casting

This is when you convert a bigger size tire for a smaller type size. And it is manually done by putting the type in parentheses at the front of the value:

Illustration

Type conversion Methods

Built-in methods can be used to convert data types explicitly such as, convert.ToDouble, convert.Tostring, convert.ToInt64(long), convert.ToInt22 (int) and convert.ToBoolean):

Illustration

C# User Input

C# User Input

Get user input

Username inputted by the user in the illustrated example can be stored in variable username the user value of his name will be printed.

Illustration

User inputs and numbers

A string is returned When the console.ReadLine() method is used. Therefore, information from another cannot be seen. The program will display an error.

Illustration

This will be the display the message.

Type 'string' cannot be converted to 'int'

In the previous chapter we have taught you that you cannot convert any type explicitly, make use of convert. To method;

Illustration

Keep in mind- inputting wrong or numerical input an error message to be displayed (e.g. systemformat Exception: wrong format for inputted string).

C# Operators

C# Operators

In C# programming, operations are performed on values of variables by using the operator

In the illustrated example below the + operator is used to join or add two values together.

Illustration

The + operator can also be used to add value and a variable or adding two variables together

Illustration

Value plus value

Value plus variable

Variable plus variable

Variable + value

Arithmetic operators

List of arithmetic operators for mathematic operators

Addition

subtraction

multiplication

division

modulus

increment

decrement

Operator          Name ​                                    Description ​                                                  Example             

+ ​          Addition                  two values are Added together ​              x + y             

- ​          Subtraction             one value is subtracted from another ​             x - y             

* ​          Multiplication          two values are Multiplier ​                                  x * y                 

/ ​          Division ​     one value is divided by another ​              x / y             

% ​          Modulus ​     Returns the division remainder ​              x % y             

++ ​          Increment ​      The value of a variable is increased by                  1   x++             

-- ​          Decrement               the value of a variable is Decreases by                  1   x--             

C# Assignments Operators

To assign variable to values, assignment operators are used to perform this function

C# Logical Operators

To determine logic between values and variables logical operators are used for this function.

Operator ​    Name ​                Description ​                                                           Example

&& ​ Logical and        Returns true if both statements are true ​                   x < 5 &&  x < 10

|| ​ Logical or ​            Returns true if one of the statements is true              x < 5 || x < 4

! ​ Logical not        Reverse the result, returns false if the result is true              !(x < 5 && x < 10)

C# Math

C# Math

In C# programming, mathematical task on numbers are done , math class have different methods that enables this operation

Math.Max(x,y)

To find the highest value of x and y, the math.max(x,y) method used to perform this operation.

Math.Min (x,y)

To find the lowest value of x and y the math.min method is used to perform this operation.

Math.Sqrt(x)

To return the square root of x, the math.sqrt(x) method is used to perform this operation.

Math.abs(x)

Returning absolute positive value x, Math.abs(x) method is used to perform is operation.

Math.Round()

To round the number to nearest whole number, math.Round() method is used to perform this operation.

C# Strings

C# Strings

For storing text in c#, Strings are used to perform these tasks.

A string variable contains an assembly of characters enclosed by double quotes

illustration

A variable of type string, Create and assign value to it:

String length

In C# programming, string is an object property, method embedded in it, which can perform operations on string. The length property can search out the length of a string.

Illustration

Other methods

Other available strings (Toupper() and ToLower() both returning copy of the strings that are converted to uppercase or lowercase.

Illustration

String concatenation

Using the + operator to combine strings is known as concatenation.

Illustration

Space is in between the first name and the last name is added to create space on print.

Concatenating two strings can be done using string.concat() method.

String interpolation .

String interpolation can be used in place of string concatenation but on string interpolation you don't have to worry about space.

Interpolation substitute values of variables into placeholders in a string.

Illustration

Keep in mind- the $ sign must be used when making use of string interpolation method.

Access strings

Character in a string can be accessed when you refer to it index number inside square box []

Keep in mind - in C# programming, the first character is [0], the second character is [1]. string index in C#

programming begins with 0

In myString, the second character is printed

Illustration

Index position of a string can be located when you make use of indexof() method.

Characters or slash are can be extracted from a string using a method called substring () beginning from the specified character/ index /position and back to the new string. In most cases the substring() and indexof () a used alongside each other.

illustration

Special character

As explained in previous chapters, string is used within quotes to avoid errors.

In C# programming, when placing special characters in strings using\escape character is necessary to avoid error due to the fact that special characters turn into string characters with the help of the backslash escape character.

Illustration

Keep in mind - Special characters are turn into string characters with the help of the backslash escape character.

Escape character ​ Result ​             Description

\' ​                               ' ​           Single quote

\" ​                              " ​           Double quote

\\ ​                               \ ​           Backslash

A double quote is inserted into a string with the sequence \"

Illustration

A single quote is inserted into a string with the sequence \'

A single backslash is inserted into a string with the sequence \\

Adding numbers and strings

+ Operator is used by c# programming to add addition and concatenated.

the outcome of adding two numbers is illustrated in the example below (adding two numbers=number)

illustration

Ouput= 35, Because Z will be an integar

The outcome of adding two strings is illustrated below (adding two strings=concatenation).

Illustration

Output= 1520 , z will be a string

C# Booleans

C# Booleans

The application of data type in programming is always needed (data type with one of two values)

True or false

yes or no

On or off

The bool data type decision programming has values of either true or false

Boolean values

Bool keyword is used to declare a Boolean type and can use the values true or false

illustration

Based on conditional testing, returning Boolean values from expression is common.

Boolean Expression

An expression that returns a Boolean value in C# programming is called a Boolean expression.

To find if an expression or a variable is true making use of a comparison operator (E.G greater than) will get the job done for you.

Illustration

Or

The equal to (==) operator is used to evaluate an expression In the examples below,

in C# programming, comparison and conditions at the basics of the Boolean value of an expression.

C# If...Else

C# If...Else

C# conditions and if statements

Logical conditions in mathematics are supported by C# programming

Less than or equal to: a <= b

Greater than: a > b

Less than: a < b

Equal to a == b

Greater than or equal to: a >= b

Not Equal to: a != b

Different decisions for several actions can be performed using these conditions.

Conditional statement in C# programming

You can specify a block of code to be executed, by Making Use of (if) Statement, when a specified condition is true

You can specify a block of code to be executed by Making Use of (else) Statement, When the same condition is false

You can specify a new condition to test by Making Use of (else if) Statement, When the first condition is false

You can specify several alternative blocks of code to be executed, by making Use of switch 

The if Statement

To specify a block of C# code that needs to be executed if the condition is true, use the if statement.

Syntax

Keep in mind- if should always be in a lowercase, using uppercase with generate error.

Two values are tested to check if 30 is greater than 15 in the illustration below

In the illustration above, x and y are two variables both are used as test in order for us to check if x is greater than y- the greater operator is used to perform this operation.

We can identify that 30 (x) is greater than 15 (y), so the output is x is greater than y.

The else statement

To specify a block of C# code that needs to be executed if the condition is false, using the else statement is used to get the job done.

Syntax

Illustration

The else if statement

if the first condition is false, the use of the else if statement to specified condition can be used

Syntax

Illustration

In the illustrated example above, 30 (Times) is greater than 15, which indicates, the first above condition is false.

else if statement in the condition, is false as well, since condition 1 and condition 2 are false we move to else condition- then print "Good evening".

Short Hand if….Else (Ternary Operator)

Short hand if... Else consist of 2 operands that why is called the Ternary operator, multiple lines of code can be replaced with a single line, using short-hand if else, it can as well replace simple if else statements.

Syntax

In its place of writing

Write This

Illustration

C# Switch

C# Switch

C# switch Statements

To select one of several code blocks to execute making use of a switch statement can get the job done for you.

Syntax

How it works

It is evaluated once (switch expression)

default and break keywords

the block of code (Associated) will be executed if there is a match.

the values of each case and value of the expression are compared with each other.

illustration

The Break Keyword

The C# breaks out the switch blocks if it switches a break keyword- stopping the execution of more codes, also inside the block (case testing will stop as well)

A lot of time of execution is saved using the break keyword, because in the switch box everyday codes is ignored

The default Keyword

If there's no case match the default keyboard specifies some code to run and is also optional.

Illustrated example

C# While Loop

C# While Loop

Loops

As long as a specified condition is reached loops will execute a block of code.

Loop save times and are handy due to the fact that they reduce errors and help us to understand, and make our codes more readable.

As long as a variable is less than 6, illustrated example below the loop run many times.

Illustration

Keep in mind - remember the loop will continue to increase, if the variable used in the condition is not increased by you.

The Do/While Loop

This is a variant of the while loop. before checking if the condition is true, the code block will be executed by the loop once, if the condition is true, it will repeat itself.

Syntax

Remember, if the condition is false, the do while loop condition will be executed once despite the condition is false because it is executed before the condition is tested.

C# for Loop

C# for Loop

The for loop is used instead of the while loop when you know the exact times you want to loop through the block of code.

Syntax

Statement 1 - Before executions of the code block this one is executed once.

Statement 2 - Conditions for executing the code block is defined by statements 2.

Statement 3 - after execution of the code block statement 2 is executed every time.

Illustration

Explanation

Statement 1 - Before the loop start (int 1= 0) statement 1 sets a variable.

Statement 2 - For the loop to run (one must be less than 6) statement you must define the conditions, the loop will end itself, if the condition is false, but if it is true the loop will continue.

Statement 3 -Every time the code (in the loop is executed) it increases in value (I++)

Illustration 2

The values between 0 – 20 is printed out

The foreach loop

This is used to look through elements in an array.

Syntax

How to put all elements in the car array in the illustrated example below.

Illustration

C# Break and Continue

C# Break and Continue

C# Break

As explained earlier C# break are used in the C# programming to "jump out" of a switch statement.

To jump out of a loop the break statement can also be used.

Refer to this illustrated example below

C# Continue

Whenever a specified condition occurs, in the loop, one iteration will break, and continue with following iteration in the loop. The continue statements is responsible for all this process.

The value of 5 is skipped in the example

Illustration

Break and continue in While Loop

In while loop, break and continue can be used

Illustration-Break

Illustration Continued

C# Arrays

C# Arrays

In place of declaring separate variables for each value, and storing multiple values in a single variable, arrays are responsible for this.

Use the square brackets to define the variable type

A variable that holds an array of strings is being declared

An array literal is used to insert values to it- in a comma separated list and curly braces place the values.

create an array of integers by writing

Access the elements of an array

By referring to index number we can access an array element.

The value of the first element in cars is been assessed by the statements below.

Illustration

Change and array elements

By referring to the index number automatically change the value of a specific element

illustration

Array Length

The length property is used to know the number of elements an array has

Illustration

Output=4

Loop through an array

for loop are used to loop through the other elements, and to specify how many times the loop should run the length property is used.

All elements in the cars  array in the following example are outputted.

Illustration

The foreach Loop

In C# programming to loop through element in an array the for each loop is used.

Syntax

In the illustrated explanation, the for each loop is used to output all elements in the cars arrays

illustration

Comparing the for loop and the for each loop, you will noticed using the for each method is very easy, because (using the length property) it not necessary to have a counter.

Sort Arrays

This helps to sort an array in an ascending order or alphabetically, different array methods that are available for use. The sort() is part of them.

Illustration

System.Linq Namespace

Important array methods are, Min,Sum and Max,you can find all this in system.Linq namespace:

Illustration

Other ways to create and array

Due to the fact that you are a beginner you might not be familiar with array created with the new keyword, but if you are familiar with C# programming you must have come across this method. there are multiple ways you can create an array.

But due to the example given above the last option is easier to read and faster to learn.

Having said that, making use of the [new keyword] is best option, to declare an array and initialize it later.

new keyword:

C# Method

C# Methods

This is a block of code which only runs when called. Parameters can be passed into a method

methods are also known as functions they are particularly used to perform certain actions.

Methods are also used [to reuse a code], define the code and at the same time use it many times.

Create a method

The name of a method is used to define the method followed by parentheses (). There are some methods you're already familiar with which are provided by C# programming (pre-defined methods).

I want to perform some certain actions you can as well create your own methods.

Illustration

Inside the program class create a method

Explaining the example

The name of the method is (MyMethod)

Static -This indicates that it does not belongs to an object of the program class but it belongs to the program class itself.

Void - This shows that it(method) does not have a return value.

Keep in mind - When naming methods in C# programming it is best to start with uppercase letter in other for the code to be readable for you and every other person that come across the code.

Call a method

The method name followed by two parentheses coupled with a semicolon; are used to execute a method.

in the illustrated example below to print a text MyMethod is used, when it's called.

Illustration

Possible to call a method multiple time:

C# Method Parameters

C# Method Parameters

Parameters and Arguments

As parameters information are passed to methods because inside the method parameters act as variables.

After the method name inside the parentheses, parameters are specified. Adding many parameters is allowed in C# programming, you just have to separate them with a comma.

Fname is a string but in the illustrated example below it is taken as a parameter,

Illustration

Argument is when a parameter is passed to the method. Carefully study the above illustration.

John

Jacob

Amaya

These three are argument

Fname---- Parameter

Default parameter value

A default parameter value can be used, using equal sign (=). If the method is called without arguments the default value is used- and the default value in the example is (" Germany "):

Optional parameter is a parameter with a default value. The illustrated the example above tells you the two things if carefully studied.

(1)                         " Germany" = the default value

(2)                         " Country" = the optional parameter

Multiple parameters

Having several parameters is allowed.

Illustration

Keep in mind ----- The number of the method called must be equal to the number of arguments as there as parameters, whenever you are working with multiple parameters- and in the same order, the arguments must be passed.

Return Values

In the illustration above, the new keyword is Used in the example, indicating the method should not return value, use primitive data type (int or double) to return a value, make use of the return keyword inside the method, instead of void keyword

The sum of a method (two parameters) is returned in the example below,

The result can be stored in a variable (for easy readability).

illustration

Named Arguments

Key: value syntax can be used to send arguments

Order of arguments doesn't matter.

When you have multiple parameters coupled with default value, argument are very useful; specifying one of them whenever you call, it will only be necessary.

C# Method Overloading

C# Method Overloading

Method Overloading

Methods (different)--- with method overloading they have the same name with different parameters.

Illustration

Reflect on the subsequent example, which include two methods that add numbers of dissimilar type:

illustration

it is advisable to overload one method instead of defining two methods doing the same thing.

In the illustrated example below, use PlusMethod method to work for (int and double).

Illustration

Keep in mind - As long as the number or type of parameters are different, multiple methods can have the same name.

C# OOP

C#- What is OOP

Writing procedures or methods that performs operations on the data is called procedural programming when it comes to object orientated programming it is creating objects that I have both data and methods]

OOP- object-oriented programming

When it comes to object-oriented programming it has so many advantages that we can talk about over procedural programming

Advantages of object-oriented programming

For programs it provides a clear structure.

They are faster to execute

They're easier to execute

They make C# codes easier to maintain, modify, and the dubug.

Creating full reusable application, OOP makes it possible with fuel code and less development time.

Keep in mind -Reducing the reputation of code. the don't repeat yourself principle makes this possible in C# programming.

So instead of repeating codes you should place them at a single place then reuse them and make sure you take out codes that are common for the application.

C#- What are Classes and Objects

the two main important aspect in object-oriented programming are classes and objects.

In the following image below let us check difference between class and object

Class                                           objects

Fruits​ ​                Watermelon

Orange

Pineapple

An object is an instance of a class Wylie class is template for Objects.

So, all variables and methods from the class are inherit when the individual objects are created.

C# Classes and Objects

Classes and Objects

As we have mention earlier in the previous chapters that C# is viewed as object-oriented programming language.

Note- please make sure you keep this in mind and which is useful for you now and whenever you are using the c# code.

all (attributes and methods), (classes and objects) all these are related and associated with the C# programming.

Let's take for instance, a phone is an object, has method such as the keypad, and has attributes such as the weights and size.

Create a Class

The class keyword is used to create a class

let create a class  -Class= "Car" and a variable color:

Field is when a variable is declared in a class directly. And Field can also be called attributes.

Using uppercase for the first letter winning in classes is required for a better result but not necessary. And also, another for us to organize our code we need to name the c# and the class the same name. Is an appropriate thing to do but not required.

Create an Object

From a class is how an object is being created, a class has already been created and it named 'phone' with this info an object can be created.

Now specify the class name in order for you to create an object for phone and make the use of new keyword (the keyword - new).

Illustration

Print the value of colour:  by creating an object called " myObj"

For us to access the variable inside the class(myObj.colour) we make use of the dot Syntex (.)

Multiple Objects

Multiple objects of one class can be created:

illustration

Create two objects of Car:

USING MULTIPLE CLASSES

Creating an object of a class and assessing it in another class is very possible. This helps the classes to be more organized. The main () is in one class, while the other methods and fields in another class.

Car.cs

Program.cs

if you clearly observe you will notice the public keyword called access modifier, this helps to specify the color variable or phone and other classes can access it as well classes such as program.

C# Class Members

Class Members

The class members consist of fields and methods both are referred to as fields and method class members.

illustration

Used two fields and one method (three class members) to create a Car class.

Fields

You have learnt previously that a variable inside the class is/ are called Fields. In the previous chapter and you can only access them by using syntax to create an object of the class.

With myObj, you will create an object of the "car class" in the illustrated example, and then value of the field color and maxSpeed are printed.

Illustration

When creating the objects leave the fields blank and modify them, when creating multiple objects of one class this is very important and useful.

illustration

When creating multiple objects of one class, this very vital and helpful.

illustration

Objects Methods

Previously we learnt that method in C# programming are used to perform certain actions. Object defines how will objects of the class behaves and method belongs to a class, dot syntax are used to access a method, similarly to how we can access 'Fields'. But keep in mind method must be public.

Keep in mind that the name of method with two parameters, then followed by semicolon (;) are used to execute the method.

Questions must have been running through your mind, such as method is declared as public, why? Not static

Reasons

Without you creating an object of the class static method can be accessed but in the case of public method it can only be accessed by objects.

Use Multiple Classes

As discussed in the last chapters multiple classes are used for better organization (one class for execution while the other class for method and Field).

We used car.cs as case study previously, we will still be using car.cs

Car.cs

Program.cs

The public keyword specifies that the fields of.  Car can be accessed by other classes such as program. And they are called an access modifier.

C# Constructors

C# Constructors

In C# programming, constructors are used to initialize objects, and it's a very special method in C# programming.

Illustration

Whenever an object of a class is created that is when the constructor come to play/or being used, this is one of the advantages of constructor. Also, to set initial value for Fields, a constructor can be used for this function.

Keep in mind

The name given to the constructor on the class name must be the same, and a return type keyword such as (void or int) must not be included.

As we have said earlier when the object is created that is when the contructor is called, Keep it in mind.

C# automatically create a class constructor for you by default, if you don't create one, by default in c# all classes have constructor. So setting initial values for Fields is not possible for you.

They (Constructors) save time.

Constructor Parameters

Parameters can be used to initialize Fields, which means Constructors can make use of them.

Illustration

You can as well overload constructor by making use of different parameters.

Constructors Saves time

The amount of code used when using constructors are lesser and this helps to save time, this makes them very useful and productive for programmers.

Without using constructor

Programs.cs

With constructor

Program.cs

C# Access Modifies

C# Access Modifies

Access Modifies

The public keyword has been repeated severally in our previous illustrations, which you have come across severally and now you are familiar with it.

Illustration

public string color;

The Public keyword- are used to set the access visibility for Fields, method, properties, and classes. they are access Modifier.

Access modifier in C# Programming

Public - All classes have the access to the code

Private - The code can only be used/ access within the same class.

Protected - the code can only be accessed within the same class or a class inherited from that particular Class.

Internal- you can only access the code inside its own assembly.

Two combinations

Private protected

Protected internal

But we will only focus on private and public modifiers.

Private modifier

A field with a private access modifier can only be accessed within the same class if declared.

Illustration

Output- Venza

Accessing it outside the class, will display an error message.

Output will be

'Car.model' is difficult to get to because of its security (been protected) level

The field 'Car.model' is assigned, however its value is by no means used

Public modifier

A field with a public access modifier can access all classes if declared.

The output will be: Venza

Access Modifies?

the visibility of the class member is controlled when using access modifiers, and also the security level of all individual class.

Encapsulation can be defined as a way or a process of keeping "sensitive" data hidden from users. And this can be achieved when you declare the field is private.

Keep in mind - if don’t specify an access modifier, all members of a class are private by default.

Illustration

C# Properties (Get and Set)

C# Properties (Get and Set)

Properties and Encapsulation

Having a basic knowledge of encapsulation is vital before we begin to explain properties.

Encapsulation can be defined as a way or a process of keeping sensitive data hidden from users.

Basic things to do in Encapsulation

Fields/variable declared as private.

Through properties you must provide get, sets, and public methods.

Properties

Within the same class is where you can only access private variables, (that is you can't access it outside class).

But sometimes we need to access them which is made possible by using properties.

Property-this is the combination of a method and a variable. Property has two methods which are a set method and a get method:

Illustration

The value of a variable name is returned by the get method.

A value to the name variable is assigned by the set method. the value assigned to the property is represented by the value keyword.

So, in order for us to access, then go on to update the private field of the person class we need to use the name property to perform this operation.

Illustration

Output will be - Jacob

Automatic Properties (Short Hand)

Making use of the shorthand/automatic properties is provided by c#, which means you do not need to define the field for the property, you just have to write get; and set; inside the property.

The above illustration and below illustration output the same results but the difference between them is one having lesser code.

Illustration

Output will be =Jacob

Encapsulation

Why Encapsulation

Keep your data safe, high level of security.

Part of the code can be changed easily by the programmer without affecting the other codes.

By making use of the get method, the fields will be read- only, on the other hand, using the set method only, you are making the fields write-only.

You have more and total control of class members, helping you or anyone avoid messing the code.

C# Inheritance

C# Inheritance

Inheritance (Base and Derived Class)

In C# programming, fields and methods from one class to another is very possible, so the "Inheritance concept" are grouped into three categories which are listed below,

Base Class (parent)

Derived Class (child)

The: symbol are used to inherit from a class.

From the vehicle (class) parents is where the car class (child) inherit the fields and methods from, in the illustrated example below:

Illustration

When to use "inheritance", and why using them

For code reusability, inheritance is very useful- when you needed to create a new class, using the fields and methods of existing class is made possible.

The sealed keyword

The sealed keyword is used if you don't want other classes to inherit from a particular Class.

Assessing a sealed class in c# programming will produce or generate an error:

C# Polymorphism

C# Polymorphism

Polymorphism and overriding

Whenever you come across Polymorphism, it signifies 'many forms' when many classes are similar to each other by Inheritance, it means Polymorphism have occurred.

Like we have mentioned in the previous chapters, we can inherit fields and methods from another class by using inheritance, so those methods and fields used by Polymorphism performing a single action in separate ways if possible, with Polymorphism.

Let's use a base called animal which has the sound called animalsound(). Animal derived class might be dog cats, etc. They also have animal sounds (e.g. Cat- meows)

Illustration

We previously told you: symbol can be used to inherit from a class.

Let's use the animalsound () method to call the cow and bird objects, we want to create.

Illustration

Output will be

The animal makes a sound

Output am not expecting .

You might not be expecting the above output they happen due to the fact that the derived class method is override by base class method, sharing the same name.

by adding virtual keyword provided by C# to the method, overrides the base method, also make use of override keyword for individual derived class method.

Illustration

When to use 'inheritance and Polymorphism'

For code readability

C# Abstraction

C# Abstraction

Abstract Classes and Methods

Displaying message information to end users and keeping a particular information (important) is called data abstraction.

Abstract class or interface can be used to achieve abstraction.

Abstract keyword

These are used for classes and methods.

Abstract class : this cannot be used to create objects. It is a restricted class (you must inherit it from another class to access it).

Abstract method : abstract method doesn’t have a body. it can be used in an abstract class, derived class (inherited from) provides the body.

Regular and abstract method can have an abstract class.

Creating an object of the animal class is not possible.

An abstract class can only be accessed if inherited by another. Use Polymorphism to convert animal class to an abstract class.

When to use abstract class and methods.

This helps to secure certain details only vital information on an object are displayed.

Keep in mind with interfaces abstraction can be achieved.

Illustration

C# Interface

C# interface

Interface helps to achieve abstraction in C#. Interface contains abstract properties and method (with the void bodies). It is completely an abstract class.

Illustration

Starting interface with "I" is required, for you to identify the difference between interface and class when coding.

Abstraction and the public and members of an interface by default.

Keep in mind properties and methods are inside interface excluding Fields.

The interface must be inherited or (implemented) to gain access to interface method. (:) Symbol is used to implement ( inherit) an interface. the implements class provides the body of the interface method. keep in mind that override keyword is not used when implementing an interface.

Illustration

Notes on interfaces

In creating an object, interfaces cannot be used

The body is provided by "implemented class" interface method has no body.

Overriding on its method is required when implementing an interface.

fields and variable are not inside interface but can contain methods and properties.

Abstract and public are members of interface by default.

interface cannot create objects; you will not find constructor inside them (interface).

When to use interface and why we use them.

Multiple inheritance is not supported by c# (from one base class is where a class can inherit from). nevertheless, interfaces make it possible for multiple inheritance to be achieved in c Sharp, the class can implement multiple interfaces.

Keep in mind - separate with a comma to implement multiple interfaces.

Multiple interfaces

Separate with a comma to implement multiple interfaces.

C# Enum

C# Enum

The special class represents group of constants, the Enum is created by using the Enum keyword, instead of using interface or class, use Enum keyword to create Enum. With a comma separate to Enum items.

Illustration

With dot syntax, access the Enum.

Enum means specifically listed-and it pronounced ' enumerations'

Enum inside a class

Enum can be found inside a class.

Illustration

The output will be High

Enum value

First item in Enum value is 0, while the second value is 1 and so on by default.

Converting explicitly the item to an int: is the only way to get integer value from an item.

Illustration

The output will be 6

Assigning your own Enum value and next item will automatically update the next number.

Enum in a switch statement

To check for corresponding values, Enum are used in switch statements.

Illustration

The output is High Level

C# Files

C# files

Working with files

For us to be able to work with files, we make use of the file class from System.io

Illustration

Forgetting information or creating information, the file class has several methods to perform this task.

Write to a file and read it

We created a with file WriteAllText() method and named "filename.txt" , the ReadAllText() method is used to read contents.

Illustration

Ouput will be

Good morning!

C# Exception

C# Exception

Situation arises when it comes to coding programmers making errors due to wrong inputs and so many issues when executing the C# code.

C# stop and display error message when an error occurred. So, when an error occurred in C# it is called Exception.

C# Try and Catch

Defining a block of code for testing (to check

Errors) at the time of being executed, is allowed by a try statement

Defining a block of code to be executed is allowed by catch statement, if an error is detected in the try block.

They are both in pairs (catch and try keywords)

Syntax

An array of these three integers is created in the illustrated example

MyNumber(10) does not exist so an error will be generated.

Example of the error message

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

If we detect an error the try... Catch can be used to catch the error and some code can be used to execute. To deal with the situation.

Variable inside the catch block (c) coupled with built-in message property, output message that describes the exception, are used in the example below.

Illustration

Your own error or can be outputted

Illustration

Finally

in spite of the results, final statement allows you to say execute code after try...catch

Illustration

The Throw keyword

Custom error is created by using the throw statements

But exception class and throw statements are used together in c#. In c# exception class is available.

Write the list below

FileNotFoundException,

TimeOutException,

ArithmeticException,  

IndexOutOfRangeException.

Illustration

Displayed error message in the program.

C# How to add two numbers

Add two numbers

How to add two numbers in C#.