0% found this document useful (0 votes)
5 views

C# Fundamentals (1)

This document serves as an introductory guide to C# programming, covering essential tools, syntax, and concepts such as variables, data types, operators, and control structures. It provides step-by-step instructions for setting up Visual Studio, creating a console application, and writing basic C# code, including comments and methods. The document emphasizes understanding foundational concepts to enhance coding skills and maintainability.

Uploaded by

ITview WORLD
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C# Fundamentals (1)

This document serves as an introductory guide to C# programming, covering essential tools, syntax, and concepts such as variables, data types, operators, and control structures. It provides step-by-step instructions for setting up Visual Studio, creating a console application, and writing basic C# code, including comments and methods. The document emphasizes understanding foundational concepts to enhance coding skills and maintainability.

Uploaded by

ITview WORLD
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 63

C#

fundamenta
ls

Chigbo Evans Chinedu


(KceeGudMan)
Focus on
your
journey !
Tools And Tips

• Visual Studio (2019/2022)


• Stack Overflow
• Google
• Code Along
• Don’t skip assignments and projects
Installing
visual
studio
Visual studio is an integrated
development environment used to edit
and compile code.
In our tutorial we will use visual studio
community which is the free version of
visual studio.
Download installer
https://visualstudio.microsoft.com/vs/communit
Create
New Project
Click on the lunch Button to get
started with visual studio.

Create a new project.


Console
Application
Select console application as
the project type.
Ensure it’s - Console App(.NET
Core)
Click Next ….
Configure
Your new
project
Enter project name e.g. Hello World.
Select the location you want to save
your project.
Click on Create.
Visual studio will automatically
generate a new code.
Your First
Code Project.
Congratulation you have just created
your first c# project 😘😊😜
C# syntax
In the previous slide, we created a C# file called Program.cs,
and we used the following code to print "Hello World" to the
screen:
Syntax Explained
• using System, we are using classes from the system
namespace
• A blank line. C# ignores white spaces. However multiple
lines makes the code more readable.
• namespace is used to organize your code and it’s a
container for classes and other name spaces.
• The curly braces {} marks the beginning and end of a
block of code.
• class is a container for data and method, which brings
functionality to your program. Every line of code that runs
in c# must be inside a class. In our example we named
the class “Program”.
Syntax Explained
• Another thing that always appears in C# is the main method.
Any code inside its curly brackets {} will be executed. The main
method is the entry point of our application. It is where the
execution of our program starts from.

• Console is a class of the system name space, which has a


WriteLine() method that is used output/print text. In our example
“Hello World”.

• If you omit the using System line, you would have to write
System.Console.WriteLine() to print/output text.

• Every C# statement ends with a semicolon ; .

• C# is case-sensitive; "MyClass" and "myclass" have different


meaning.
Confused ?
😒
Don't worry if you don't understand how
using System, namespace and class
works. Just think of it as something that
(almost) always appears in your program,
and that you will learn more about them
in a later sections.
C#
Comments
Comments can be used to explain C#
code, and to make it more readable. It can
also be used to prevent execution when
testing alternative code.
Single-Line Comments / Multi-Line
Comments

Single-line comments start with two Multi-line comments start with /* and
forward slashes ( // ). ends with */.

Any text between // and the end of the Any text between /* and */ will be
line is ignored by C# (will not be ignored by C#. Meaningful eye contact
executed).
C#
Variables
Variables are containers for storing data
values. In C#, there are different types of
variables (defined with different keywords).
 int - stores integers (whole numbers), without
decimals, such as 123 or -123

 double - stores floating point numbers, with


decimals, such as 19.99 or -19.99

 Char - stores single characters, such as 'a' or 'B'.


Char values are surrounded by single quotes

 string - stores text, such as "Hello World". String


values are surrounded by double quotes
 bool - stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, you must specify the
type and assign it a value:

Examples of
variables in C#
Creating A
Variable
Creating A
Variable
Re-Assign
Value
Varieties of
types

Great Time
spent 😍
C#
Constants
If you don’t want others or yourself to
overwrite existing values, you can add the
const keyword in front of the variable type.
This will declare the variable as “constant”
which means unchangeable and read-only.
C#
Identifiers
All c# variables must be identified with
unique names. This unique name are
called identifiers.
It is recommended to use descriptive
name in other to create understandable
and maintainable code.
Data Type Size Description
A data type specifies
the size and type of Stores whole numbers from -
variable values. int 4 bytes 2,147,483,648 to
2,147,483,647
It is important to use Stores whole numbers from -
the correct data type long 8 bytes 9,223,372,036,854,775,808 to
for the 9,223,372,036,854,775,807
corresponding Stores fractional numbers.
variable; to avoid float 4 bytes Sufficient for storing 6 to 7
decimal digits
errors, to save time
and memory, but it Stores fractional numbers.
will also make your double 8 bytes Sufficient for storing 15 decimal
digits
code more
maintainable and
readable. bool 1 bytes Stores true or false values

Data Types In C#
Data Type Size Description
A data type specifies
the size and type of Stores a single
variable values. char 2 bytes character/letter, surrounded
by single quotes
It is important to use
the correct data type Stores a sequence of
for the string 8 bytes characters, surrounded by
corresponding double quotes
variable; to avoid
errors, to save time
and memory, but it
will also make your
code more
maintainable and
readable.

Data Types In C#
Numbers

Number types are divided into two  Even though there are
groups: many numeric types in C#,
 Integer types stores whole numbers, the most used for numbers
positive or negative (such as 123 or - are int (for whole numbers)
456), without decimals. Valid types are and double (for floating
int and long. Which type you should point numbers). However,
use, depends on the numeric value. we will describe them all
as you continue to read.
 Floating point types represents
numbers with a fractional part,
containing one or more decimals. Valid
types are float and double.
Value Types & Reference Types

 Value types directly contain their data.  In C#, data types are
When you create a value type variable, the broadly categorized into
variable holds the actual value, not a two main types: value
reference to it. Value types are stored in the
stack memory (unless they are part of a
types and reference types.
reference type, in which case they are Understanding the
stored in the heap). difference between these
two is crucial for effective
 Reference Types store a reference (or memory management and
memory address) to the actual data, which performance optimization
is stored in the heap memory. When you in C#.
create a reference type variable, the
variable holds a pointer to the memory
location where the data is stored.
Examples of Value Point Explanation
Types
Stored in Stack Value types are typically stored in the stack,
Primitive Types - int, Memory which makes them faster to access.
float, double, char, When you assign a value type to another
bool, etc. variable or pass it to a method, a copy of the
Copy by Value value is created. Changes to the copy do not
Structs – Custom affect the original.
structures defined using Value types cannot be null (unless they are
the struct keyword. Default Values nullable, e.g., int?). They have default values
(e.g., 0 for int, false for bool).
Enums - User-defined Value types have a fixed size determined at
enumerations. Fixed Size compile time.

Value Types In C#
Value Types

Code Sample:
Examples of Point Explanation
Reference Types
Stored in Heap Reference types are stored in the heap, which
Classes - Custom Memory allows for dynamic memory allocation.
classes defined using the
class keyword. When you assign a reference type to another
variable or pass it to a method, both variables
Arrays – Single- Copy by Reference point to the same memory location. Changes
dimensional or multi-
to one variable affect the other.
dimensional arrays.
Strings - The string Default Values The default value of a reference type is null.
type is a reference type.
Delegates – Function Reference types can grow or shrink in size
Dynamic Size dynamically (e.g., arrays, strings).
pointer
Interfaces - Reference
types that define
contracts.

Reference Types In C#
Reference Types

Code Sample:
Boxing & Unboxing

 Boxing : Converting a value type to a


reference type (e.g., storing an int in
an object).

 Unboxing : Converting a reference


type back to a value type.

 Boxing and unboxing have


performance overhead, so they should
be used judiciously.
Implicit Casting
Explicit Casting

Type casting is when you assign a value of one data type to another type.

Implicit Casting (automatically) - Explicit Casting (manually) –


converting a smaller type to a larger converting a larger type to a smaller
type size char -> int -> long -> float -> type size double -> float -> long -> int
double -> char
Type Conversion Methods

It is also possible to convert data types explicitly by using built-in methods, such as
Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int) and
Convert.ToInt64 (long):
Why Conversion?

Many times, there's no need for type conversion. But sometimes you
have to when working with user input, We would see an example in
the next chapter.
C# Operators

Operator Name Description Example

Adds together two


+ Addition x+y
values
Subtracts one value
- Subtraction x-y
from another

* Multiplication Multiplies two values x*y

Divides one value by


/ Division x/y
another
Returns the division
% Modulos x%y
remainder
C# Operators

Operator Name Description Example

Increases the value of


++ increment x++
a variable by 1
Decreases the value
-- Decrement of a variable by 1 x--
C# Assignment Operators

Operator Name Description Example

Assign Add value to


= Equal to Int x = 3
variable

+= Plus equal to Add value to variable Int x += 2

Subtract value from


-= Minus equal to Int x -= 4
variable
Multiply value from
*= Times equal to Int x *= 4
variable
Divide value from
/= Divide equal to Int x /= 2
variable
C# Comparison Operators

Operator Name Example

== Equal to x==y

!= Not equal x != y

> Greater than x>y

< Less than x<y


Greater than or equal
>= x >= y
to
C# Strings

String Length:

A string in C# is actually an object, which contain properties and methods that can
perform certain operations on strings. For example, the length of a string can be
found with the Length property:
C# String Concatenation

String Concatenation

The + operator can be used between strings to combine them. This is called
concatenation
C# String Interpolation

String Interpolation
Another option of string concatenation, is string interpolation, which substitutes
values of variables into placeholders in a string. Note that you do not have to worry
about spaces, like with concatenation:
C# If ... Else

The if Statement

Use the if statement


to specify a block of
C# code to be
executed if a
condition is True.
C# The else Statement

The else Statement

Use the else


statement to specify a
block of code to be
executed if the
condition is False.
C# The else if Statement

The else if Statement

Use the else if statement


to specify a new
condition if the first
condition is False.
C# Short Hand If...Else

Short Hand If...Else (Ternary


Operator)
There is also a short-hand if else, which is known as the ternary operator because it
consists of three operands. It can be used to replace multiple lines of code with a
single line. It is often used to replace simple if else statements:
C# While Loop
Loops
Loops can execute a block of
code as long as a specified
condition is reached.
Loops are handy because they
save time, reduce errors, and
they make code more readable.

C# While Loop
The while loop loops
through a block of code
as long as a specified
condition is True:
The Do/While Loop

The do/while loop is a variant of


the while loop. This loop will
execute the code block once,
before checking if the condition is
true, then it will repeat the loop
as long as the condition is true.
The example below uses a
do/while loop. The loop will
always be executed at least
once, even if the condition is
false, because the code block is
executed before the condition is
tested:
C# For Loop

When you know exactly how


many times you want to loop
through a block of code, use the
for loop instead of a while loop:

Statement 1: is executed (one time)


before the execution of the code block.
Statement 2: defines the condition for
executing the code block.
Statement 3: is executed (every time)
after the code block has been executed.
The foreach Loop

There is also a foreach loop,


which is used exclusively to loop
through elements in an array (or
other data sets):

The following example outputs all


elements in the cars array, using a
foreach loop:
C# Break

The break statement can also be


used to jump out of a loop.

This example jumps out of the


loop when i is equal to 4:
C# Continue

The continue statement breaks


one iteration (in the loop), if a
specified condition occurs, and
continues with the next iteration
in the loop.
This example skips the value of
4:
Break and Continue in While
Loop
You can also use break and
continue in while loops:
C# Arrays
Create an Array
Arrays are used to store multiple
values in a single variable, instead of
declaring separate variables for each
value.

To declare an array, define


the variable type with
square brackets:
Access the Elements of an Array

You access an array element by


referring to the index number.

This statement accesses the value


of the first element in cars:
C# Methods
Create a Method
A method is defined with the name of
the method, followed by parentheses
A method is a block of code which (). C# provides some pre-defined
only runs when it is called. methods, which you already are
familiar with, such as Main(), but you
You can pass data, known as can also create your own methods to
parameters, into a method. perform certain actions:

Methods are used to perform certain


actions, and they are also known as
functions.

Why use methods? To reuse code:


define the code once, and use it
many times.
C# Methods

Example Explained

MyMethod() is the name of the method

static means that the method belongs to the Program class and not an
object of the Program class. You will learn more about objects and how
to access methods through objects later in this tutorial.

void means that this method does not have a return value. You will
learn more about return values later in this chapter
Call a Method

To call (execute) a method, write the method's name followed by two


parentheses () and a semicolon;

In the following example, MyMethod() is used to print a text (the


action), when it is called:

Example (In Next Slide)

Inside Main(), call the myMethod() method:


Call a Method
C# Method Parameters
Parameters and Arguments
Information can be passed to methods as parameter.
Parameters act as variables inside the method.
They are specified after the method name, inside the
parentheses. You can add as many parameters as you want,
just separate them with a comma.
Default Parameter Value
You can also use a default parameter value, by
using the equals sign (=).

If we call the method without an argument, it


uses the default value
Method Parameters
C# Return Values

In the previous page, we used the


void keyword in all examples, which
indicates that the method should
not return a value.

If you want the method to return a


value, you can use a primitive data
type (such as int or double) instead
of void, and use the return keyword
inside the method:
C# Method Overloading

With method overloading, multiple


methods can have the same name
with different parameters:
Thank you
Chigbo Evans Chinedu

You might also like