Comprog Q4 Week 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

11

1
COMPUTER
PROGRAMMING.NET

Quarter 4
Week 1

ANTONIO D. MONTEMAYOR
B.S. Computer Science, B.S.Elementary Education ,M.A. Educational
Management 39 units., M.A. Information Technology 12 units

Learner’s Material
What This Module is About
This module is all about how to develop ASP.NET MVC 5 Applications . Students should know
how to perform Object-Oriented Programming with C# . And also to learn how to program in C#
using Visual Studio 2013 or higher and programming language provided to support .NET
Framework development.

What I need to Know


AT THE END OF THIS MODULE, YOU SHOULD BE ABLE TO:

DEVELOP ASP.NET MVC 5 WEB APPLICATIONS (DAMWA)

LO 2 - Perform Object-Oriented Programming with C#

2.1 Describe the architecture of .NET Framework applications and use the features that Visual Studio
2013 or higher and programming language provided to support .NET Framework development.

2.2 Use the basic data types, operators, and expressions

2.3 Use the constructed standard programming language

2.4 Use the created and invoked methods, passed parameters to methods, and returned values from
methods

2.5 Create overloaded methods and use optional & output parameters

HOW TO LEARN FROM THIS MODULE


o To achieve the objectives cited above, you are to do the following:
o Take your time reading the lessons thoroughly and carefully.
o Follow the instructions in the activities and exercises diligently.
o Answer all the given tests and exercises.
ICONS OF THIS MODULE
What I need to This part contains learning
Know objectives that are set for you
to learn as you go along the
module.
What I know This is an assessment as to
your level of knowledge to
the subject matter at hand,
meant specifically to gauge
prior related knowledge.
What’s In This part connects previous
lesson with that of the current
one.
What’s New An introduction of the new
lesson through various
activities, before it will be
presented to you.
What is it These are discussions of the
activities as a way to deepen
your discovery and
understanding of the concept.

What’s More These are follow-up activities


that are intended for you to
practice further in order to
master the competencies.

What I have Learned Activities designed to process


what you have learned from
the lesson.
What I can do These are tasks that are
designed to showcase your
skills and knowledge gained,
and applied into real-life
concerns and situations.
Assessment These are tasks to gauge the
learner’s learning and
feedback.

What I Know
C# (C-Sharp) is a programming language developed by Microsoft that runs on the .NET Framework.

C# is used to develop web apps, desktop apps, mobile apps, games and much more.

What is C#?

C# is pronounced "C-Sharp".
It is an object-oriented programming language created by Microsoft that runs on the .NET
Framework.

C# has roots from the C family, and the language is close to other popular languages
like C++ and Java.

The first version was released in year 2002. The latest version, C# 8, was released in September
2019.

C# is used for:

• Mobile applications
• Desktop applications
• Web applications
• Web services
• Web sites
• Games
• VR
• Database applications
• And much, much more!

Why Use C#?

• It is one of the most popular programming language in the world


• It is easy to learn and simple to use
• It has a huge community support
• C# is an object oriented language which gives a clear structure to programs and allows code
to be reused, lowering development costs.
• As C# is close to C, C++ and Java, it makes it easy for programmers to switch to C# or vice
versa

What’s in
C# Get Started
C# IDE

The easiest way to get started with C#, is to use an IDE.

An IDE (Integrated Development Environment) is used to edit and compile code.

In our tutorial, we will use Visual Studio Community, which is free to download
from https://visualstudio.microsoft.com/vs/community/.
Applications written in C# use the .NET Framework, so it makes sense to use Visual Studio, as the
program, the framework, and the language, are all created by Microsoft.

C# Install

Once the Visual Studio Installer is downloaded and installed, choose the .NET workload and click on
the Modify/Install button:

After the installation is complete, click on the Launch button to get started with Visual Studio.

On the start window, choose Create a new project:

Then click on the "Install more tools and features" button:


Choose "Console App (.NET Core)" from the list and click on the Next button:

Enter a name for your project, and click on the Create button:
Visual Studio will automatically generate some code for your project:

What’s New

2.1 Describe the architecture of .NET Framework applications and use the features that Visual Studio
2013 or higher and programming language provided to support .NET Framework development.

What is .NET Framework? Explain Architecture & Components

2.11 What is .Net Framework?

.Net Framework is a software development platform developed by Microsoft for building and
running Windows applications. The .Net framework consists of developer tools, programming
languages, and libraries to build desktop and web applications. It is also used to build websites,
web services, and games.

The .Net framework was meant to create applications, which would run on the Windows Platform.
The first version of the .Net framework was released in the year 2002. The version was called .Net
framework 1.0. The Microsoft .Net framework has come a long way since then, and the current
version is .Net Framework 4.7.2.

The Microsoft .Net framework can be used to create both - Form-based and Web-
based applications. Web services can also be developed using the .Net framework.

The framework also supports various programming languages such as Visual Basic and C#. So
developers can choose and select the language to develop the required application. In this chapter,
you will learn some basics of the .Net framework.

In this .Net Architecture tutorial, you will learn .NET Framework basics-

• .Net Framework Architecture


• .NET Components
• .Net Framework Design Principle
.Net Framework Architecture

.Net Framework Architecture is a programming model for the .Net platform that provides an
execution environment and integration with various programming languages for simple
development and deployment of various Windows and desktop applications. It consists of class
libraries and reusable components.

The basic architecture of the .Net framework is as shown below.

.Net Framework Architecture Diagram

.NET Components

The architecture of .Net framework is based on the following key components;

1. Common Language Runtime

The "Common Language Infrastructure" or CLI is a platform in .Net architecture on which the
.Net programs are executed.

The CLI has the following key features:

• Exception Handling - Exceptions are errors which occur when the application is executed.

Examples of exceptions are:

o If an application tries to open a file on the local machine, but the file is not present.
o If the application tries to fetch some records from a database, but the connection to
the database is not valid.
• Garbage Collection - Garbage collection is the process of removing unwanted resources
when they are no longer required.

Examples of garbage collection are

o A File handle which is no longer required. If the application has finished all
operations on a file, then the file handle may no longer be required.
o The database connection is no longer required. If the application has finished all
operations on a database, then the database connection may no longer be required.
• Working with Various programming languages –

As noted in an earlier section, a developer can develop an application in a variety of .Net


programming languages.

1. Language - The first level is the programming language itself, the most common ones are
VB.Net and C#.
2. Compiler – There is a compiler which will be separate for each programming language. So
underlying the VB.Net language, there will be a separate VB.Net compiler. Similarly, for
C#, you will have another compiler.
3. Common Language Interpreter – This is the final layer in .Net which would be used to run
a .net program developed in any programming language. So the subsequent compiler will
send the program to the CLI layer to run the .Net application.

2. Class Library

The .NET Framework includes a set of standard class libraries. A class library is a collection of
methods and functions that can be used for the core purpose.

For example, there is a class library with methods to handle all file-level operations. So there is a
method which can be used to read the text from a file. Similarly, there is a method to write text to
a file.

Most of the methods are split into either the System.* or Microsoft.* namespaces. (The asterisk *
just means a reference to all of the methods that fall under the System or Microsoft namespace)

A namespace is a logical separation of methods. We will learn these namespaces more in detail in
the subsequent chapters.
3. Languages

The types of applications that can be built in the .Net framework is classified broadly into the
following categories.

• WinForms – This is used for developing Forms-based applications, which would run on an
end user machine. Notepad is an example of a client-based application.
• ASP.Net – This is used for developing web-based applications, which are made to run on
any browser such as Internet Explorer, Chrome or Firefox.
o The Web application would be processed on a server, which would have Internet
Information Services Installed.
o Internet Information Services or IIS is a Microsoft component which is used to
execute an Asp.Net application.
o The result of the execution is then sent to the client machines, and the output is
shown in the browser.
• ADO.Net – This technology is used to develop applications to interact with Databases such
as Oracle or Microsoft SQL Server.

Microsoft always ensures that .Net frameworks are in compliance with all the supported Windows
operating systems.

.Net Framework Design Principle

Now in this .Net Architecture tutorial, we will learn the design priciples of .Net framework. The
following design principles of the .Net framework is what makes it very relevant to create .Net
based applications.

1. Interoperability - The .Net framework provides a lot of backward support. Suppose if you
had an application built on an older version of the .Net framework, say 2.0. And if you
tried to run the same application on a machine which had the higher version of the .Net
framework, say 3.5. The application would still work. This is because with every release,
Microsoft ensures that older framework versions gel well with the latest version.
2. Portability- Applications built on the .Net framework can be made to work on any
Windows platform. And now in recent times, Microsoft is also envisioning to make
Microsoft products work on other platforms, such as iOS and Linux.
3. Security - The .NET Framework has a good security mechanism. The inbuilt security
mechanism helps in both validation and verification of applications. Every application can
explicitly define their security mechanism. Each security mechanism is used to grant the
user access to the code or to the running program.
4. Memory management - The Common Language runtime does all the work or memory
management. The .Net framework has all the capability to see those resources, which are
not used by a running program. It would then release those resources accordingly. This is
done via a program called the "Garbage Collector" which runs as part of the .Net
framework.
The garbage collector runs at regular intervals and keeps on checking which system
resources are not utilized, and frees them accordingly.

5. Simplified deployment - The .Net framework also have tools, which can be used to package
applications built on the .Net framework. These packages can then be distributed to client
machines. The packages would then automatically install the application.

Summary

• .Net is a programming language developed by Microsoft. It was designed to build


applications which could run on the Windows platform.
• The .Net programming language can be used to develop Forms based applications, Web
based applications, and Web services.
• Developers can choose from a variety of programming languages available on the
Microsoft .Net framework platform. The most common ones are VB.Net and C#.

What is it
C# Syntax
Program.cs
using System;

namespace HelloWorld

class Program

static void Main(string[] args)

Console.WriteLine("Hello World!");

Line 1: using System means that we can use classes from the System namespace.
Line 2: A blank line. C# ignores white space. However, multiple lines makes the code more
readable.

Line 3: namespace is a used to organize your code, and it is a container for classes and other
namespaces.

Line 4: The curly braces {} marks the beginning and the end of a block of code.

Line 5: class is a container for data and methods, 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.

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 chapter.

Line 7: Another thing that always appear in a C# program, is the Main method. Any code inside
its curly brackets {} will be executed. You don't have to understand the keywords before and after
Main. You will get to know them bit by bit while reading this tutorial.

Line 9: Console is a class of the System namespace, which has a WriteLine() method that is
used to output/print text. In our example it will output "Hello World!".

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

Note: Every C# statement ends with a semicolon ;.

Note: C# is case-sensitive: "MyClass" and "myclass" has different meaning.

Note: Unlike Java, the name of the C# file does not have to match the class name, but they often
do (for better organization). When saving the file, save it using a proper name and add ".cs" to the
end of the filename. To run the example above on your computer, make sure that C# is properly
installed: Go to the Get Started Chapter for how to install C#. The output should be:

Hello World!
WriteLine or Write

The most common method to output something in C# is WriteLine(), but you can also
use Write().

The difference is that WriteLine() prints the output on a new line each time,
while Write() prints on the same line (note that you should remember to add spaces when needed,
for better readability):
Example

Console.WriteLine("Hello World!");

Console.WriteLine("I will print on a new line.");

Console.Write("Hello World! ");

Console.Write("I will print on the same line.");

Result:

Hello World!
I will print on a new line.
Hello World! I will print on the same line.

VELOP ASP.NET MVC 5 WEB APPLICATIONS (DAMWA)


LO 2 - Perform Object-Oriented Programming with C#

What’s More

2.2 Use the basic data types, operators, and expressions


C# Variables

Variables are containers for storing data values.

In C#, there are different types of variables (defined with different keywords), for example:

• 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:

Syntax

type variableName = value;

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

To create a variable that should store text, look at the following example:

Example

Create a variable called name of type string and assign it the value "John":

string name = "John";

Console.WriteLine(name);

To create a variable that should store a number, look at the following example:

Example

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;

Console.WriteLine(myNum);

int myNum;

myNum = 15;

Console.WriteLine(myNum);

Note that if you assign a new value to an existing variable, it will overwrite the previous value:

Example

Change the value of myNum to 20:

int myNum = 15;

myNum = 20; // myNum is now 20

Console.WriteLine(myNum);
The const keyword is useful when you want a variable to always store the same value, so that
others (or yourself) won't mess up your code. An example that is often referred to as a constant, is
PI (3.14159...).

Note: You cannot declare a constant variable without assigning the value. If you do, an error will
occur: A const field requires a value to be provided.

Other Types

A demonstration of how to declare variables of other types:

Example

int myNum = 5;

double myDoubleNum = 5.99D;

char myLetter = 'D';

bool myBool = true;

string myText = "Hello";

You will learn more about data types in the next chapter.

Display Variables

The WriteLine() method is often used to display variable values to the console window.

To combine both text and a variable, use the + character:

Example

string name = "John";

Console.WriteLine("Hello " + name);

You can also use the + character to add a variable to another variable:

Example

string firstName = "John ";

string lastName = "Doe";

string fullName = firstName + lastName;

Console.WriteLine(fullName);
For numeric values, the + character works as a mathematical operator (notice that we
use int (integer) variables here):

Example

int x = 5;

int y = 6;

Console.WriteLine(x + y); // Print the value of x + y

From the example above, you can expect:

• x stores the value 5


• y stores the value 6
• Then we use the WriteLine() method to display the value of x + y, which is 11

Declare Many Variables

To declare more than one variable of the same type, use a comma-separated list:

Example

int x = 5, y = 6, z = 50;

Console.WriteLine(x + y + z);

C# Identifiers

All C# variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

Note: It is recommended to use descriptive names in order to create understandable and


maintainable code:

Example

// Good

int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is

int m = 60;
The general rules for constructing names for variables (unique identifiers) are:

• Names can contain letters, digits and the underscore character (_)
• Names must begin with a letter
• Names should start with a lowercase letter and it cannot contain whitespace
• Names are case sensitive ("myVar" and "myvar" are different variables)
• Reserved words (like C# keywords, such as int or double) cannot be used as names

C# Data Types
C# Data Types

As explained in the variables chapter, a variable in C# must be a specified data type:

Example

int myNum = 5; // Integer (whole number)

double myDoubleNum = 5.99D; // Floating point number

char myLetter = 'D'; // Character

bool myBool = true; // Boolean

string myText = "Hello"; // String

A data type specifies the size and type of variable values. It is important to use the correct data type
for the corresponding variable; to avoid errors, to save time and memory, but it will also make your
code more maintainable and readable. The most common data types are:

Data Type Size Description

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

bool 1 bit Stores true or false values

char 2 bytes Stores a single character/letter, surrounded by single quotes

string 2 bytes per Stores a sequence of characters, surrounded by double quotes


character

Numbers

Number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are int and long. Which type you should use, depends on the numeric
value.

Floating point types represents numbers with a fractional part, containing one or more decimals.
Valid types are float and double.

Even though there are many numeric types in C#, the most used for numbers are int (for whole
numbers) and double (for floating point numbers). However, we will describe them all as you
continue to read.

Integer Types
Int

The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in
our tutorial, the int data type is the preferred data type when we create variables with a numeric
value.

Example

int myNum = 100000;

Console.WriteLine(myNum);
Long

The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note that you
should end the value with an "L":

Floating Point Types

You should use a floating point type whenever you need a number with a decimal, such as 9.99 or
3.14515.

Float

The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you
should end the value with an "F":

Example

float myNum = 5.75F;

Console.WriteLine(myNum);

Double

The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you
can end the value with a "D" (although not required):

Example

double myNum = 19.99D;

Console.WriteLine(myNum);

Use float or double?

The precision of a floating point value indicates how many digits the value can have after the
decimal point. The precision of float is only six or seven decimal digits, while double variables
have a precision of about 15 digits. Therefore it is safer to use double for most calculations.

Scientific Numbers

A floating point number can also be a scientific number with an "e" to indicate the power of 10:

Example

float f1 = 35e3F;
double d1 = 12E4D;

Console.WriteLine(f1);

Console.WriteLine(d1);

Booleans

A boolean data type is declared with the bool keyword and can only take the
values true or false:

Example

bool is CSharpFun = true;

bool is FishTasty = false;

Console.WriteLine(isCSharpFun); // Outputs True

Console.WriteLine(isFishTasty); // Outputs False

Boolean values are mostly used for conditional testing, which you will learn more about in a later
chapter.

Characters

The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':

Example

char myGrade = 'B';

Console.WriteLine(myGrade);

Strings

The string data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes:

Example

string greeting = "Hello World";

Console.WriteLine(greeting);

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):

Example

int myInt = 10;

double myDouble = 5.25;

bool myBool = true;

Console.WriteLine(Convert.ToString(myInt)); // convert int to string

Console.WriteLine(Convert.ToDouble(myInt)); // convert int to double

Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int

Console.WriteLine(Convert.ToString(myBool)); // convert bool to string

C# User Input
Get User Input

You have already learned that Console.WriteLine() is used to output (print) values. Now we
will use Console.ReadLine() to get user input.

In the following example, the user can input his or hers username, which is stored in the
variable userName. Then we print the value of userName:

Example

// Type your username and press enter

Console.WriteLine("Enter username:");

// Create a string variable and get user input from the keyboard and store it in the variable

string userName = Console.ReadLine();

// Print the value of the variable (userName), which will display the input value

Console.WriteLine("Username is: " + userName);

User Input and Numbers


The Console.ReadLine() method returns a string. Therefore, you cannot get information from
another data type, such as int. The following program will cause an error:

Example

Console.WriteLine("Enter your age:");

int age = Console.ReadLine();

Console.WriteLine("Your age is: " + age);

The error message will be something like this:

Cannot implicitly convert type 'string' to 'int'

Like the error message says, you cannot implicitly convert type 'string' to 'int'.

Luckily, for you, you just learned from the previous chapter (Type Casting), that you can convert
any type explicitly, by using one of the Convert.To methods:

Example

Console.WriteLine("Enter your age:");

int age = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Your age is: " + age);

C# Operators
C# Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example

int x = 100 + 50;

Although the + operator is often used to add together two values, like in the example above, it
can also be used to add together a variable and a value, or a variable and another variable:

Example

int sum1 = 100 + 50; // 150 (100 + 50)


int sum2 = sum1 + 250; // 400 (150 + 250)

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 x++

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

int sum3 = sum2 + sum2; // 800 (400 + 400)

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations:

C# Assignment Operators

Assignment operators are used to assign values to variables.


In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:

Example

int x = 10;

The addition assignment operator (+=) adds a value to a variable:

Example

int x = 10;

x += 5;

A list of all assignment operators:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3
&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3


Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

C# Comparison Operators

Comparison operators are used to compare two values:

C# Logical Operators

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 !(x < 5 && x <
is true 10)

Logical operators are used to determine the logic between variables or values:

C# Strings
C# Strings

Strings are used for storing text.

A string variable contains a collection of characters surrounded by double quotes:

Example

Create a variable of type string and assign it a value:

string greeting = "Hello";

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:

Example

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

Console.WriteLine("The length of the txt string is: " + txt.Length);

Other Methods

There are many string methods available, for example ToUpper() and ToLower(), which returns a
copy of the string converted to uppercase or lowercase:

Example

string txt = "Hello World";


Console.WriteLine(txt.ToUpper()); // Outputs "HELLO WORLD"

Console.WriteLine(txt.ToLower()); // Outputs "hello world"

String Concatenation

The + operator can be used between strings to combine them. This is called concatenation:

Example

string firstName = "John ";

string lastName = "Doe";

string name = firstName + lastName;

Console.WriteLine(name);

Note that we have added a space after "John" to create a space between firstName and lastName
on print.

You can also use the string.Concat() method to concatenate two strings:

Example

string firstName = "John ";

string lastName = "Doe";

string name = string.Concat(firstName, lastName);

Console.WriteLine(name);

C# Arithmetic Operators

What is Arithmetic Operator?

• How to use Arithmetic operator in program?


• What is Escape Character and how to use it?

Operators are a very useful thing in computing value. While writing a program, you need various
types of operators to calculate the value. These operators are categorized as different categories in
C sharp tutorial that performs specific task ex. The C# arithmetic operator performs the basic
calculation as add, subtraction, multiplication, division, and modulus whereas other operators
perform a different kind of task. You will learn one by one all these operators in few next chapters.
Arithmetic Operators are used for basic mathematical calculation in C# programming. The list of
Arithmetic Operators is given below:

ARITHMETIC OPERATORS:

Operator Description Examples

+ Add numbers X=num1+num2

- Subtract numbers X=num1-num2

* Multiply numbers X=num1*num2

/ Divide numbers X=num1/num2

% Divide two numbers and returns reminder X=22%10 then X will be X=2

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5.
6. namespace Arithmetic_Operators
7. {
8. class Program
9. {
10. static void Main(string[] args)
11. {
12. int num1, num2;
13. int add, sub, mul;
14. float div;
15.
16. //Accepting Values from users
17. Console.Write("Enter first number\t\t");
18. num1 = Convert.ToInt32(Console.ReadLine());
19.
20. Console.Write("\n\nEnter second number\t\t");
21. num2 = Convert.ToInt32(Console.ReadLine());
22.
23. //Processing Values
24. //Used + operator for adding values
25. add = num1 + num2;
26. //Used - operator for subtracting values
27. sub = num1 - num2;
28. //Used * operator for multiplying values
29. mul = num1 * num2;
30. //Used / operator for dividing values
31. div = (float)num1 / num2;
32.
33. //Displaying Output
34. Console.WriteLine("\n\n=====================\n");
35. Console.WriteLine("Addition\t\t{0}", add);
36. Console.WriteLine("Subtraction\t\t{0}", sub);
37. Console.WriteLine("Multiplication\t\t{0}", mul);
38. Console.WriteLine("Division\t\t{0}", div);
39. Console.WriteLine("\n=======================\n");
40.
41. Console.ReadLine();
42. }
43. }
44. }

Output
Enter first number 15

Enter second number 12

=====================

Addition 27

Subtraction 3

Multiplication 180

Division 1.25

=======================
__

Note: \t,\n these are the special characters in C# that is known as Escape Characters. It is
used for special purpose such as inserting line break, backspace etc.

2.4 Use the created and invoked methods, passed parameters to methods, and returned values
from methods

C# Methods

A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

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.

2.5 Create overloaded methods and use optional & output parameters
Create a Method

A method is defined with the name of the method, followed by parentheses (). C# provides some
pre-defined methods, which you already are familiar with, such as Main(), but you can also
create your own methods to perform certain actions:

Example

Create a method inside the Program class:

class Program

static void MyMethod()

// code to be executed

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

Note: In C#, it is good practice to start with an uppercase letter when naming methods, as it
makes the code easier to read.

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

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

static void MyMethod()

Console.WriteLine("I just got executed!");

static void Main(string[] args)

MyMethod();

// Outputs "I just got executed!"

A method can be called multiple times:

Example

static void MyMethod()

Console.WriteLine("I just got executed!");


}

static void Main(string[] args)

MyMethod();

MyMethod();

MyMethod();

// I just got executed!

// I just got executed!

// I just got executed!

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.

The following example has a method that takes a string called fname as parameter. When the
method is called, we pass along a first name, which is used inside the method to print the full
name:

Example

static void MyMethod(string fname)

Console.WriteLine(fname + " Refsnes");

static void Main(string[] args)

{
MyMethod("Liam");

MyMethod("Jenny");

MyMethod("Anja");

// Liam Refsnes

// Jenny Refsnes

// Anja Refsnes

When a parameter is passed to the method, it is called an argument. So, from the example
above: fname is a parameter, while Liam, Jenny and Anja are arguments.

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 ("Norway"):

Example

static void MyMethod(string country = "Norway")

Console.WriteLine(country);

static void Main(string[] args)

MyMethod("Sweden");

MyMethod("India");

MyMethod();

MyMethod("USA");

}
// Sweden

// India

// Norway

// USA

A parameter with a default value, is often known as an "optional parameter". From the example
above, country is an optional parameter and "Norway" is the default value.

Multiple Parameters

You can have as many parameters as you like:

Example

static void MyMethod(string fname, int age)

Console.WriteLine(fname + " is " + age);

static void Main(string[] args)

MyMethod("Liam", 5);

MyMethod("Jenny", 8);

MyMethod("Anja", 31);

// Liam is 5

// Jenny is 8

// Anja is 31

Note that when you are working with multiple parameters, the method call must have the same
number of arguments as there are parameters, and the arguments must be passed in the same order.

Return Values
The void keyword, used in the examples above, 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:

Example

static int MyMethod(int x)

return 5 + x;

static void Main(string[] args)

Console.WriteLine(MyMethod(3));

// Outputs 8 (5 + 3)

This example returns the sum of a method's two parameters:

Example

static int MyMethod(int x, int y)

return x + y;

static void Main(string[] args)

Console.WriteLine(MyMethod(5, 3));

// Outputs 8 (5 + 3)

You can also store the result in a variable (recommended, as it is easier to read and maintain):
Example

static int MyMethod(int x, int y)

return x + y;

static void Main(string[] args)

int z = MyMethod(5, 3);

Console.WriteLine(z);

// Outputs 8 (5 + 3)

Named Arguments

It is also possible to send arguments with the key: value syntax.

That way, the order of the arguments does not matter:

Example

static void MyMethod(string child1, string child2, string child3)

Console.WriteLine("The youngest child is: " + child3);

static void Main(string[] args)

MyMethod(child3: "John", child1: "Liam", child2: "Liam");

// The youngest child is: John


Named arguments are especially useful when you have multiple parameters with default values, and
you only want to specify one of them when you call it:

Example

static void MyMethod(string child1 = "Liam", string child2 = "Jenny", string child3 = "John")

Console.WriteLine(child3);

static void Main(string[] args)

MyMethod("child3");

// John

2.5 Create overloaded methods and use optional & output parameters

C# Method Overloading
Method Overloading

With method overloading, multiple methods can have the same name with different parameters:

Example

int MyMethod(int x)

float MyMethod(float x)

double MyMethod(double x, double y)

Consider the following example, which have two methods that add numbers of different type:

Example

static int PlusMethodInt(int x, int y)

{
return x + y;

static double PlusMethodDouble(double x, double y)

return x + y;

static void Main(string[] args)

int myNum1 = PlusMethodInt(8, 5);

double myNum2 = PlusMethodDouble(4.3, 6.26);

Console.WriteLine("Int: " + myNum1);

Console.WriteLine("Double: " + myNum2);

Instead of defining two methods that should do the same thing, it is better to overload one.

In the example below, we overload the PlusMethod method to work for both int and double:

Example

static int PlusMethod(int x, int y)

return x + y;

static double PlusMethod(double x, double y)

return x + y;
}

static void Main(string[] args)

int myNum1 = PlusMethod(8, 5);

double myNum2 = PlusMethod(4.3, 6.26);

Console.WriteLine("Int: " + myNum1);

Console.WriteLine("Double: " + myNum2);

Note: Multiple methods can have the same name as long as the number and/or type of
parameters are different.

What I have Learned

Insert the missing part of the code below to output "Hello World!".

1.static void (string[] args)

{
. ("Hello World!");
}
2.Create a variable named myNum and assign the value 50 to it.

= ;

3. Add the correct data type for the following variables:

myNum = 9;
myDoubleNum = 8.99;
myLetter = 'A';
myBoolean = false;
myText = "Hello World";
4. Fill in the missing parts to get user input, stored in the variable userName:

Console.WriteLine("Enter username:");
userName = Console. ;
Console.WriteLine("Username is: " + userName);

5. Exercise:

Multiply 10 with 5, and print the result.

Console.WriteLine(10 5);

6. Fill in the missing part to create a greeting variable of type string and assign it the value Hello.

= ;

7. Create a method named MyMethod and call it inside Main().

static void ()
{
Console.WriteLine("I just got executed!");
}

static void Main(string[] args)


{

What I Can Do
Give the Output of the following code:
1.
using System;

namespace TypeConversionApplication {
class StringConversion {
static void Main(string[] args) {
int i = 75;
float f = 53.005f;
double d = 2345.7652;
bool b = true;
Console.WriteLine(i.ToString());
Console.WriteLine(f.ToString());
Console.WriteLine(d.ToString());
Console.WriteLine(b.ToString());
Console.ReadKey();

}
}
}

2. using System;

namespace VariableDefinition {
class Program {
static void Main(string[] args) {
short a;
int b ;
double c;

/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
3. using System;

namespace EscapeChar {
class Program {
static void Main(string[] args) {
Console.WriteLine("Hello\tWorld\n\n");
Console.ReadLine();
}
}
}
4. using System;

namespace DeclaringConstants {
class Program {
static void Main(string[] args) {
const double pi = 3.14159;

// constant declaration
double r;
Console.WriteLine("Enter Radius: ");
r = Convert.ToDouble(Console.ReadLine());

double areaCircle = pi * r * r;
Console.WriteLine("Radius: {0}, Area: {1}", r,
areaCircle);
Console.ReadLine();
}
}
}

5. Calling Methods in C#

You can call a method using the name of the method. The following example illustrates
this −
using System;

namespace CalculatorApplication {
class NumberManipulator {
public int FindMax(int num1, int num2) {
/* local variable declaration */
int result;

if (num1 > num2)


result = num1;
else
result = num2;
return result;
}

static void Main(string[] args) {


/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();
//calling the FindMax method
ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
}

Assessment 1:

1. Write a C# Sharp program to print Hello and your name in a separate line. Expected Output :
Hello: Alexandra Abramov
2. Write a C# Sharp program to print the sum of two numbers.

3. Write a C# Sharp program to print the result of dividing two numbers.

4. Write a C# Sharp program to print the result of the specified operations.

• -1 + 4 * 6

• ( 35+ 5 ) % 7

• 14 + -4 * 6 / 11

• 2 + 15 / 6 * 1 - 7 % 2

Expected Output:
23
5
12
3
5. Write a C# Sharp program to swap two numbers.
Input the First Number : 5
Input the Second Number : 6
Expected Output:
After Swapping :
First Number : 6
Second Number : 5
6. Write a C# Sharp program to print the output of multiplication of three numbers which will be
entered by the user.

Input the first number to multiply: 2


Input the second number to multiply: 3
Input the third number to multiply: 6
Expected Output:
2 x 3 x 6 = 36
7. Write a C# Sharp program to print on screen the output of adding, subtracting, multiplying and
dividing of two numbers which will be entered by the user.

Input the first number: 25


Input the second number: 4
Expected Output:
25 + 4 = 29
25 - 4 = 21
25 x 4 = 100
25 / 4 = 6
25 mod 4 = 1
8. Write a C# Sharp program that takes a number as input and print its multiplication table.
Test Data:
Enter the number: 5
Expected Output:
5*0=0
5*1=5
5 * 2 = 10
5 * 3 = 15
....
5 * 10 = 50
9. Write a C# Sharp program that takes four numbers as input to calculate and print the average.

Enter the First number: 10


Enter the Second number: 15
Enter the third number: 20
Enter the four number: 30

ExpectedOutput:
The average of 10 , 15 , 20 , 30 is: 18
10. Write a C# Sharp program to that takes three numbers(x,y,z) as input and print the output
of (x+y).z and x.y + y.z. Enter first number - 5
Enter second number - 6
Enter third number - 7

Expected Output:
Result of specified numbers 5, 6 and 7, (x+y).z is 77 and x.y + y.z is 72

REFERENCES:
Online Resources:
What is .NET Framework? Explain Architecture & Components (guru99.com)
C# Syntax (w3schools.com)
C# Variables (w3schools.com)
C# Data Types (w3schools.com)
C# Operators (w3schools.com)

C# User Input (w3schools.com)

C# Sharp: Basic Declarations and Expressions : Exercises, Practice, Solution - w3resource

You might also like