Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views29 pages

ASP - Net Programing

Uploaded by

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

ASP - Net Programing

Uploaded by

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

03610363 - ASP.

NET Programing

UNIT: 2 Programming in C#

Overview of C#

C# is a modern, general-purpose, object-oriented programming language developed by Microsoft and


approved by European Computer Manufacturers Association (ECMA) and International Standards
Organization (ISO).

C# was developed by Anders Hejlsberg and his team during the development of .Net Framework.

C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and
runtime environment that allows use of various high-level languages on different computer platforms
and architectures.

The following reasons make C# a widely used professional language −

• It is a modern, general-purpose programming language


• It is object oriented.
• It is component oriented.
• It is easy to learn.
• It is a structured language.
• It produces efficient programs.
• It can be compiled on a variety of computer platforms.
• It is a part of .Net Framework.

Following is the list of few important features of C# −

1
03610363 - ASP.NET Programing

C# environment

C# is a general-purpose, modern and object-oriented programming language.


Basic Components involved in process of Setting up the environment in C#

1 .Net Framework

The .NET Framework is a platform for building, deploying, and running Web Services and applications.
To run C# applications or any program, it requires installing a .NET Framework component on the
system. .NET also supports a lot of programming languages like Visual Basic, Visual C++, etc. And C#
is one of the common languages which is included in the .NET Framework. It is consist of two basic
components:

• Common Language Runtime (CLR): The .NET Framework contains a run-time environment
known as CLR which runs the codes. It provides services to make the development process
easy.
• Framework Class Library(FCL): It is a library of classes, value types, interfaces that provide
access to system functionality.

2 Visual Studio IDE

Microsoft has provided an IDE(Integrated Development Environment) tool named Visual Studio to
develop applications using different programming languages such as C#, VB(Visual Basic) etc. To
install and use Visual Studio for the commercial purpose it must buy a license from Microsoft. For
learning (non-commercial) purpose, Microsoft provided a free Visual Studio Community Version.

Step 1: Download the Visual Studio Community Version

2
03610363 - ASP.NET Programing

Step 2: Run the .exe file and follow the instructions to install Visual Studio Community Version on
the system.

Step 3: Select .Net Desktop Development from the options and click to install in bottom right corner
as shown below :

3
03610363 - ASP.NET Programing

Step 4: Open it and it will be prompted to sign in for the first time. The sign-in step is optional so it
can be skipped.

Step 5: The dialog box will appear for first time only and ask to choose Development Settings and
color theme. Once select required options, click on Start Visual Studio option like as shown below :

4
03610363 - ASP.NET Programing

Step 6: To create a new console application using C#, Go to File –> New –>Project like as shown
below

Step 7: Choose Console App, write the name of the project and select location path to save project
files and then click OK like as shown below.

5
03610363 - ASP.NET Programing

Step 8: After clicking OK a predefined template will come and start writing C# code.

6
03610363 - ASP.NET Programing

Example:

// Class declaration
class Geeks {

// Main Method
static void Main(string[] args) {

// statement
// printing Hello World!
Console.WriteLine("Hello World!");

// To prevents the screen from


// running and closing quickly
Console.ReadKey();
}
}
}

Output:
Hello World!

7
03610363 - ASP.NET Programing

Datatype

C# mainly categorized data types in two types: Value types and Reference types.
Value types include simple types (such as int, float, bool, and char), enum types, struct types, and
Nullable value types.
Reference types include class types, interface types, delegate types, and array types

Example: Variables of Different Data Types


using System;
public class Program
{
public static void Main()

{
stringstringVar = "Hello World!!";
intintVar = 100;
float floatVar = 10.2f;
char charVar = 'A';
bool boolVar = true;
Console.WriteLine(stringVar);
Console.WriteLine(intVar);
Console.WriteLine(floatVar);
Console.WriteLine(charVar);
Console.WriteLine(boolVar);
}
8
03610363 - ASP.NET Programing

Output:
Hello World!!
100
10.2
A
True

Type Conversion

Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#,
type casting has two forms −
Implicit type conversion − these conversions are performed by C# in a type-safe manner. For
example, are conversions from smaller to larger integral types and conversions from derived classes to
base classes
Explicit type conversion − These conversions are done explicitly by users using the pre-defined
functions. Explicit conversions require a cast operator.
The following example shows an explicit type conversion -

usingSystem;

Namespace TypeConversionApplication{
Class Explicit_Conversion{
Static void Main(string[] args){
double d =5673.74;
inti;

// cast double to int.


i=(int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
}
9
03610363 - ASP.NET Programing

Output
5673

Variables

A variable is nothing but a name given to a storage area that our programs can manipulate.
Each variable in C# has a specific type, which determines the size and layout of the variable's
memory the range of values that can be stored within that memory and the set of operations that can
be applied to the variable.
The basic value types provided in C# can be categorized as −

Type Example

Integral types sbyte, byte, short, ushort, int, uint, long, ulong, and char

Floating point types float and double

Decimal types decimal

Boolean types true or false values, as assigned

Nullable types Nullable data types

C# also allows defining other value types of variable such as enum and reference types of variables
such as class

Defining Variables

Syntax for variable definition in C# is −


<data_type> <variable_list>;

Initializing Variables

Variables are initialized (assigned a value) with an equal sign followed by a constant expression.
variable_name = value;
Variables can be initialized in their declaration. The initializer consists of an equal sign followed
by a constant expression as −

10
03610363 - ASP.NET Programing

<data_type><variable_name> = value;

Example:-

int d =3, f =5;/* initializing d and f. */


byte z =22;/* initializes z. */
double pi =3.14159;/* declares an approximation of pi. */
char x ='x';/* the variable x has the value 'x'. */

Constants

A variable whose value can not be changed during the execution of the program is called a constant
variable.
the value can not be changed during execution of the program, which means we cannot assign
values to the constant variable at run time. Instead, it must be assigned at the compile time.

Constants are of two types

Compile time constants (const)

The compile time constants are declared by using the const keyword, in which the value can not be
changed during the execution of the program.

Syntax
intconst a=10;

Example of const variable.

using System;

Namespace UsingConst
{
Class Program
{
constint a =10;

Staticvoid Main(string[]args)
{
constint b =20;

11
03610363 - ASP.NET Programing

constint c = b + a;
Console.WriteLine(c);
Console.ReadLine();
}
}
}

The output of the above program is 30.

Some key points about const variable


• It must be assigned a value at the time of declaration.
• const only allow constant variables into the expression.
• const can be declared at the class level as well as inside the method.
• constcan not be declared using static keyword because they are by default static.
• constants are absolute constants in which their value cannot be changed or assigned at the run
time.
• constant variables are compile time variables.

Runtime constants (Readonly)

The Run time constants are declared by using the Readonly keyword which value can not be changed
during the execution of the program.

intReadonlya;or
intReadonly a=0;
Example:-
usingSystem;
usingSystem.Configuration;

namespaceUsingreadonly
{
classProgram
{
readonlyint a =10;
int b =30;
int c;
readonlystring r;
publicProgram()

12
03610363 - ASP.NET Programing

{
r =ConfigurationManager.AppSettings["DollarPrice"];
Console.WriteLine("The dollar value is:"+" "+r);
Console.WriteLine();
c = a + b;
Console.WriteLine("The addition of readonly constant and non Readonly constant is
:"+Environment.NewLine+ c);
Console.ReadLine();
}

staticvoidMain(string[]args)
{
Program p =newProgram();

Console.ReadLine();
}
}
}

Output

Some key points about const variable

• It's not just to assign a value at the time of declaration, we can also assign the value for read-only
through the constructor
13
03610363 - ASP.NET Programing

• Readonly allows, readonly constant as well as non-readonly constant variables into the
expression
• Readonly can be declared only at the class level, not inside the method.
• Readonlycan not be declared using static keywords because they are by default static.
• Readonly constant's value can be set through the reference variable.
• Readonly constant variables are a runtime time constant variable.

C# Operators

Operators in C# are special symbols that denote the operation that the program needs to perform on the operands.
For Example, they can be used to evaluate a variable or perform an operation on a variable to make a proper
expression.
C# offers a wide variety of operators such as Arithmetic operators, Relational operators, Assignment operators,
Logical operators, Unary operators, etc. In this tutorial, we will be discussing some of the important operators
along with their usage.

Arithmetic Operators

The arithmetic operator allows the program to perform general algebraic operations against numeric values.
There are five basic operators present in the C# programming language.

Addition (symbol “+”): Perform the addition of operands.


Subtraction (symbol “-“): Performs subtraction of operands.
Division (symbol “/”): Performs division of operands.
Multiplication (symbol “*”): Performs multiplication on operands.
Modulus (symbol “%”): Returns reminder after the division of integer.

These are:
Increment operator: Denoted by the symbol “++”
Decrement operator: Denoted by the symbol “- -“

Relational Operators

Any relation between the two operands is validated by using relational operators. Relational operators return Boolean
values. If the relation between two operands is successfully validated then it will return “true” and if the validation
fails then “false” will be returned.

Relational operators are mainly used in decision making or for defining conditions for loops.

14
03610363 - ASP.NET Programing

Greater than operator: (denoted by “>”): Validates greater than the relation between operands.
Less than operator: (denoted by “<“): Validates less than the relation between operands.
Equals To operator: (denoted by “==”): Validates the equality of two operands.
Greater than or equals to (denoted by “>=”): Validates greater than or equals to the relation between the two
operands.
Less than or equals to (denoted by “<=”): Validates less than or equals to the relations between the two operands.
Not equal: (denoted by “!=”): Validates not an equal relationship between the two operands.

Assignment Operators

I) Equals to (“=”): It is one of the simplest assignment operators. It assigns the value of one operand to another. i.e.
the value of the right side operand to the left side operand.
Example: a = b
(ii) Add Equal to the Assignment Operator: As the name suggests it is a combination of plus “+” and equal to
“=”. It is written as “+=” and it adds the operand at the right side to the left operand and stores the final value in the
left operand.
Example: a +=b means (a = a+b)
iii) Subtract Equal Assignment Operator: Similar to the add equals, it subtracts the value of the right operand
from the left operand and then assigns the value to the left operand.
Example: a -=b means (a = a-b)
(iv) Division Equal to the Assignment Operator: It divides the value of the right operand with the left operand
and then stores the result in the left operand.
Example: a /= b mean (a= a/b)
(v) Multiply Equal to the Assignment Operator: It multiplies the value of the right operand with the left operand
and then stores the result in the left operand.
Example: a *= b mean (a= a*b)
(vi) Modulus Equals to the Assignment Operator: It finds the modulus of the left and right operand and stores
the value in the left operand
.
Logical Operators

Logical operators are used for performing logical operations. Logical operators work with Boolean expressions and
return a Boolean value. Logical operators are used with the conditional operators in loops and decision-making
statements.
#1) Logical AND Operator
Symbol: “&&”
AND operator returns true when both the values are true. If any of the value is false then it will return false.
For example, A && B will return true if both A and B are true, if any or both of them are false then it will return
false.
#2) Logical OR Operator

15
03610363 - ASP.NET Programing

Symbol: “||”
OR operator returns true if any of the condition/operands is true. It will return false when both of the operands
are false.
For example, A || B returns true if the value of either of A or B is true. It will return false if both A and B have
false values.
#3) Logical NOT Operator
Symbol: “!”
NOT operator is used to reverse the logical conclusion of any condition. If the condition is true then it will return
false and if the condition is false then it will return true.
Example, !(A||B) returns false if “A||B” returns true and will return true if “A||B” returns false.

Decision making

Decision making structures requires the programmer to specify one or more conditions to be evaluated
or tested by the program, along with a statement or statements to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is determined to
be false.

the general form of a typical decision making structure found in most of the programming languages.

C# provides following types of decision making statements.

Sr.No. Statement & Description

1 if statement

An if statement consists of a boolean expression followed by one or more statements.

16
03610363 - ASP.NET Programing

2 if...else statement

An if statement can be followed by an optional else statement, which executes when the boolean
expression is false.

3 nested if statements

You can use one if or else if statement inside another if or else if statement(s).

4 switch statement

A switch statement allows a variable to be tested for equality against a list of values.

5 nested switch statements

You can use one switch statement inside another switch statement(s).

Loops
Looping in a programming language is a way to execute a statement or a set of statements multiple
times depending on the result of the condition to be evaluated to execute statements.

1. while loop The test condition is given in the beginning of the loop and all statements are executed
till the given boolean condition satisfies when the condition becomes false, the control will be out
from the while loop.
while (boolean condition)

{
loop statements...

}
Example:
// C# program to illustrate while loop
usingSystem;

classwhileLoopDemo
{
publicstaticvoidMain()
{
intx = 1;

// Exit when x becomes greater than 4

17
03610363 - ASP.NET Programing

while(x <= 4)
{
Console.WriteLine("parul university");

// Increment the value of x for


// next iteration
x++;
}
}
}
Output:

parul university
parul university
parul university

parul university

2. for loop
for loop has similar functionality as while loop but with different syntax. for loops are preferred when
the number of times loop statements are to be executed is known beforehand. The loop variable
initialization, condition to be tested, and increment/decrement of the loop variable is done in one line
in for loop thereby providing a shorter, easy to debug structure of looping.

for (loop variable initialization ; testing condition;


increment / decrement)
{
// statements to be executed
}
Example:
usingSystem;

classforLoopDemo
{
publicstaticvoidMain()
{
// for loop begins when x=1
// and runs till x <=4
for(intx = 1; x <= 4; x++)

18
03610363 - ASP.NET Programing

Console.WriteLine("paruluniversity");
}
}
Output:
parul university

parul university
parul university

parul university
3. do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once
before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute
again. This process repeats until the given condition becomes false.

Syntax

do {
statement(s);
} while( condition );

Example

usingSystem;

namespaceLoops{
classProgram{
staticvoidMain(string[]args){
/* local variable definition */
int a =10;

/* do loop execution */
do{
Console.WriteLine("value of a: {0}", a);
a = a +1;
}
while(a <20);
Console.ReadLine();
19
03610363 - ASP.NET Programing

}
}
}

Output

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

overview of oop͛s:
(encapsulation, inheritance, polymorphism, abstraction)

C# is an object-oriented programming language.

The four basic principles of object-oriented programming are:

• Abstraction Modeling the relevant attributes and interactions of entities as classes to define an
abstract representation of a system.
Abstraction lets you focus on what the object does instead of how it does it.

Abstraction provides you a generalized view of your classes or objects by providing relevant
information.

Abstraction is the process of hiding the working style of an object, and showing the information
of an object in an understandable manner.

Example:
abstractclassMobilePhone{
publicvoidCalling();
publicvoidSendSMS();
}

20
03610363 - ASP.NET Programing

publicclassNokia1400:MobilePhone{}
publicclassNokia2700:MobilePhone{
publicvoidFMRadio();
publicvoidMP3();
publicvoidCamera();
}
publicclassBlackBerry:MobilePhone{
publicvoidFMRadio();
publicvoidMP3();
publicvoidCamera();
publicvoidRecording();
publicvoidReadAndSendEmails();
}

• Encapsulation Hiding the internal state and functionality of an object and only allowing access
through a public set of functions.

• Wrapping up a data member and a method together into a single unit (in other words class) is
called Encapsulation.

• Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data
related to an object into that object.

• Example:
Encapsulation is like your bag in which you can keep your pen, book etcetera. It means this is the
property of encapsulating members and functions.

class Bag {
book;
pen;
ReadBook();
}

• Inheritance Ability to create new abstractions based on existing abstractions.

• When a class includes a property of another class it is known as inheritance.


• Inheritance is a process of object reusability.

21
03610363 - ASP.NET Programing

• For example, a child includes the properties of its parents.

Example:

publicclassParentClass{
publicParentClass(){
Console.WriteLine("Parent Constructor.");
}
publicvoidprint(){
Console.WriteLine("I'm a Parent Class.");
}
}
publicclassChildClass:ParentClass{
publicChildClass(){
Console.WriteLine("Child Constructor.");
}
publicstaticvoidMain(){
ChildClass child =newChildClass();
child.print();
}
}

Output

Parent Constructor.
Child Constructor.
I'm a Parent Class.

• Polymorphism Ability to implement inherited properties or methods in different ways across


multiple abstractions.

• olymorphism means one name, many forms.


• One function behaves in different forms.
• In other words, "Many forms of a single object is called Polymorphism."

22
03610363 - ASP.NET Programing

• Method Overriding differs from shadowing.


• Using the "new" keyword, we can hide the base class member.
• We can prevent a derived class from overriding virtual members.
• We can access a base class virtual member from the derived class.

Abstraction

The word abstract means a concept or an idea not associated with any specific instance.

In C# programming, we apply the same meaning of abstraction by making classes not associated with
any specific instance. Abstraction is needed when we need to only inherit from a certain class, but do not
need to instantiate objects of that class. In such a case the base class can be regarded as "Incomplete".
Such classes are known as an "Abstract Base Class".

Abstract Base Class

23
03610363 - ASP.NET Programing

There are some important points about Abstract Base Class :


1. An Abstract Base class cannot be instantiated; it means the object of that class cannot be created.
2. Class having the abstract keyword with some of its methods (not all) is known as an Abstract
Base Class.
3. Class having the Abstract keyword with all of its methods is known as pure Abstract Base Class.
4. The method of the abstract class that has no implementation is known as "operation". It can be
defined as an abstract void method ();
5. An abstract class holds the methods but the actual implementation of those methods is made in
derived class.

1. abstract class animal {


2. public abstract void eat();
3. public void sound() {
4. Console.WriteLine("dog can sound");
5. }
6. }

This is the Abstract Base Class, if I make both of its methods abstract then this class would become a
pure Abstract Base Class.

Now, we derive a class of 'dog' from the class animal.

1. abstract class animal {


2. public abstract void eat();
3. public void sound() {
4. Console.WriteLine("dog can sound");
5. }
6. }
7. class dog: animal {
8. public override void eat() {
9. Console.WriteLine("dog can eat");
10. }
11. }

you can see we have 2 methods in the Abstract Base Class, the method eat() has no implementation; that
is why it is being declared as 'abstract' while the method sound() has its own body so it is not declared as
'abstract'.

In the derived class, we have the same name method but this method has its body.

We are doing abstraction here so that we can access the method of the derived class without any trouble.

24
03610363 - ASP.NET Programing

1. class program
2. {
3. abstract class animal
4. {
5. public abstract void eat();
6. public void sound()
7. {
8. Console.WriteLine("dog can sound");
9. }
10. }
11. class dog : animal
12. {
13. public override void eat()
14. {
15. Console.WriteLine("dog can eat");
16. }
17. }
18. static void Main(string[] args)
19. {
20. dog mydog = new dog();
21. animal thePet = mydog;
22. thePet.eat();
23. mydog.sound();
24. }
25. }

Finally, we created an Object 'mydog' of class dog, but we didn't instantiate any object of Abstract Base
Class 'animal'
Classes and Objects in C#

A class is a user-defined blueprint or prototype from which objects are created.


Basically, a class combines the fields and methods(member function which defines actions) into a single unit.
In C#, classes support polymorphism, inheritance and also provide the concept of derived classes and base
A class is a data structure in C# that combines data variables and functions into a single unit. Instances
of the class are known as objects. While a class is just a blueprint, the object is an actual instantiation of
the class and contains data. The different operations are performed on the object.

Class Definition

A new class requires a class definition.


It starts with the class keyword and contains the class name.

25
03610363 - ASP.NET Programing

It also includes the attributes and modifiers of the class as well as its interfaces.
Then the class body is provided within curly braces.
The syntax of a class definition is given as follows:

AccessSpecifier class NameOfClass

// Member variables

// Member functions

In the above syntax, AccessSpecifier provides the access specifier for the class.
Then the keyword class is used which is followed by the NameOfClass.
Then the class body is provided.

Object Definition
An object is a dynamically created instance of the class. It is created at runtime so it can also be called a
runtime entity. All the members of the class can be accessed using the object.
The object definition starts with the class name followed by the object name. Then the new operator is
used to create the object.
The syntax of the object definition is given as follows

NameOfClassNameOfObject = new NameOfClass();

In the above syntax, NameOfClass is the class name followed by the NameOfObject which is the object
name.
A program that demonstrates class definition and object definition is given as follows:
Source Code: Program that demonstrates class definition and object definition in C#

26
03610363 - ASP.NET Programing

using System;
namespace ClassDemo
{
class Sum
{
private int x;
private int y;
public void setVal(int val1, int val2)
{
x = val1;
y = val2;
}
public intgetSum()
{
return x + y;
}
}
class Test
{
static void Main(string[] args)
{
Sum s = new Sum();
s.setVal(3,14);
Console.WriteLine("Sum of 3 and 14 is: {0}" , s.getSum());
}
}
}
The output of the above program is given as follows:
Sum of 3 and 14 is: 17

27
03610363 - ASP.NET Programing

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.

Following are the various elements of a method −

Access Specifier − This determines the visibility of a variable or a method from another class.

Return type − A method may return a value. The return type is the data type of the value the
method returns. If the method is not returning any values, then the return type is void.

Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as
any other identifier declared in the class.

Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data
from a method. The parameter list refers to the type, order, and number of the parameters of a
method. Parameters are optional; that is, a method may contain no parameters.

Method body − This contains the set of instructions needed to complete the required activity.

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
}
}

28
03610363 - ASP.NET Programing

Call a Method

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

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

using System;

namespace MyApplication
{
class Program
{
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}

static void Main(string[] args)


{
MyMethod();
}
}
}
Output-
I just got executed!

References:
• https://www.tutorialspoint.com/asp.net/index.htm
• https://www.guru99.com/asp-net-tutorial.html
• https://www.codeproject.com/Articles/4468/Beginners-Introduction-to-ASP-NET
• https://asp.net-tutorials.com/basics/introduction/
29

You might also like