Comprog Q4 Week 1
Comprog Q4 Week 1
Comprog Q4 Week 1
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.
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.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
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!
What’s in
C# Get Started
C# IDE
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.
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.
.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 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.
.NET Components
The "Common Language Infrastructure" or CLI is a platform in .Net architecture on which the
.Net programs are executed.
• Exception Handling - Exceptions are errors which occur when the application is executed.
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.
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 –
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.
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
What is it
C# Syntax
Program.cs
using System;
namespace HelloWorld
class Program
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: 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!");
Result:
Hello World!
I will print on a new line.
Hello World! I will print on the same line.
What’s More
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
Syntax
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":
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:
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
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
Example
int myNum = 5;
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.
Example
You can also use the + character to add a variable to another variable:
Example
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;
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
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Example
// Good
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
Example
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:
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
Numbers
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
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":
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
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
Console.WriteLine(myNum);
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
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
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
Console.WriteLine(greeting);
Example
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
Console.WriteLine("Enter username:");
// Create a string variable and get user input from the keyboard and store it in the variable
// Print the value of the variable (userName), which will display the input value
Example
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
C# Operators
C# Operators
In the example below, we use the + operator to add together two values:
Example
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
Arithmetic Operators
C# Assignment Operators
Example
int x = 10;
Example
int x = 10;
x += 5;
= 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
== Equal to x == y
!= Not equal x != y
C# Comparison Operators
C# Logical Operators
&& 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
Example
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
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 Concatenation
The + operator can be used between strings to combine them. This is called concatenation:
Example
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
Console.WriteLine(name);
C# Arithmetic Operators
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:
% 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
=====================
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
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
class Program
// 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
MyMethod();
Example
MyMethod();
MyMethod();
MyMethod();
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
{
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.
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
Console.WriteLine(country);
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
Example
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
return 5 + x;
Console.WriteLine(MyMethod(3));
// Outputs 8 (5 + 3)
Example
return x + y;
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
return x + y;
Console.WriteLine(z);
// Outputs 8 (5 + 3)
Named Arguments
Example
Example
static void MyMethod(string child1 = "Liam", string child2 = "Jenny", string child3 = "John")
Console.WriteLine(child3);
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)
Consider the following example, which have two methods that add numbers of different type:
Example
{
return x + y;
return x + y;
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
return x + y;
return x + y;
}
Note: Multiple methods can have the same name as long as the number and/or type of
parameters are different.
Insert the missing part of the code below to output "Hello World!".
{
. ("Hello World!");
}
2.Create a variable named myNum and assign the value 50 to it.
= ;
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:
Console.WriteLine(10 5);
6. Fill in the missing part to create a greeting variable of type string and assign it the value Hello.
= ;
static void ()
{
Console.WriteLine("I just got executed!");
}
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;
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.
• -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.
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)