0% found this document useful (0 votes)
57 views56 pages

AWP Notes

The document discusses the .NET framework and C# programming language. It covers the following key points: - The .NET Framework includes the common language runtime (CLR) and class library. It supports multiple programming languages and provides services like memory management. - C# is a programming language that can be used to build applications on the .NET Framework. The document discusses basic C# programs, data types, and elements like namespaces and classes. - It also explains components of the .NET Framework like the base class library, CLR, and how the CLR manages execution through just-in-time compilation and garbage collection.

Uploaded by

Vikas Khandelwal
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)
57 views56 pages

AWP Notes

The document discusses the .NET framework and C# programming language. It covers the following key points: - The .NET Framework includes the common language runtime (CLR) and class library. It supports multiple programming languages and provides services like memory management. - C# is a programming language that can be used to build applications on the .NET Framework. The document discusses basic C# programs, data types, and elements like namespaces and classes. - It also explains components of the .NET Framework like the base class library, CLR, and how the CLR manages execution through just-in-time compilation and garbage collection.

Uploaded by

Vikas Khandelwal
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/ 56

Subject: Advanced Web Programming

UNIT-I

Introducing .NET: The .NET Framework, C#, VB, and the .NET Languages, The Common
Language Runtime, The .NET Class Library.

The C# Language: C# Language Basics, Variables and Data Types, Variable Operations,
Object-Based Manipulation, Conditional Logic, Loops, Methods.

Types, Objects, and Namespaces: The Basics About Classes, Building a Basic Class, Value
Types and Reference Types, Understanding Namespaces and Assemblies, Advanced Class
Programming.
--------------------------------------------------------------------------------------------------------------------------

.NET framework:
The .NET Framework is a development platform for building apps for web, Windows, Windows Phone,
Windows Server, and Microsoft Azure. It consists of the common language runtime (CLR) and the .NET
Framework class library, which includes a broad range of functionality and support for many industry
standards.

The .NET Framework provides many services, including memory management, type and memory
safety, security, networking, and application deployment. It provides easy-to-use data structures and
APIs that abstract the lower-level Windows operating system. You can use a variety of programming
languages with the .NET Framework, including C#, F#, and Visual Basic.
Components of the .Net Framework:
(i) User Interface and Program:
We can create various types of applications using .net framework such as Console
Application, Windows Application, Web application and Mobile Applications.

(ii) Base class Library:


Base class library is one of the components of the .Net Framework. It supplies a library of
base classes that we can use to implement applications quickly.

(iii) CLR (Common Language Runtime)


Common Language Runtime (CLR) is the programming (Virtual Machine component) that
manages the execution of programs written in any language that uses the .NET
Framework, for example C#, VB.Net, F# and so on. We can say that it is the heart and
soul of .Net Framework or backbone.

Common Language Runtime:


Common Language Runtime (CLR) is the programming (Virtual Machine component) that manages
the execution of programs written in any language that uses the .NET Framework, for example C#,
VB.Net, F# and so on. We can say that it is the heart and soul of .Net Framework or backbone.

Components of the CLR:


(i) CTS
Common Type System (CTS) describes a set of types that can be used in different .Net languages.
The Common Type System (CTS) ensures that objects written in different .Net languages can interact
with each other. For Communicating between programs written in any .NET compliant language, the
types have to be compatible on the basic level.
For example, C# has int Data Type and VB.Net has Integer Data Type. Hence a variable declared as int in
C# or Integer in vb.net, finally after compilation, use the same structure Int32 from CTS.

(ii) CLS
It is a subset of CTS. It defines a set of rules and restrictions that every language must follow which
runs under .NET framework. The languages which follow these set of rules are said to be CLS
Compliant. In simple words, CLS enables cross-language integration.

(iii) MSIL/IL/CIL
It is language independent code. When you compile code that uses the .NET Framework library, you
don’t immediately create an operating system - specific native code. Instead, you compile your code
into Microsoft Intermediate Language (MSIL) code or simply IL code. MSIL code is not specific to any
operating system or to any language.
Components .NET CLR and their functions
The key components of CLR includes the following:

● Class Loader - Used to load all classes at run time.


● JTI compiler- The Just In Time (JTI) compiler will convert MSIL code into native code.
● Code Manager - It manages the code at run time.
● Garbage Collector - It manages the memory. Collect all unused objects and deallocate
them to reduce memory usage.
● Thread Support - It supports multithreading of our application.
● Exception Handler - It handles exceptions at run time.

Explain how garbage collector works in .NET.


Answer:
In the common language runtime (CLR), the garbage collector serves as an automatic memory
manager.
It provides the following benefits:
❖ Enables you to develop your application without having to free memory.
❖ Allocates objects on the managed heap efficiently.
❖ Reclaims objects that are no longer being used, clears their memory, and keeps the memory
available for future allocations. Managed objects automatically get clean content to start with, so
their constructors do not have to initialize every data field.
❖ Provides memory safety by making sure that an object cannot use the content of another
object..

The managed heap:


After the garbage collector is initialized by the CLR, it allocates a segment of memory to store and
manage objects. This memory is called the managed heap, as opposed to a native heap in the
operating system.

Generations
The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage
collection primarily occurs with the reclamation of short-lived objects that typically occupy only a small
part of the heap.

There are three generations of objects on the heap:


Generation 0. : This is the youngest generation and contains short-lived objects. An example of a
short-lived object is a temporary variable. Garbage collection occurs most frequently in this
Generation. Newly allocated objects form a new generation of objects are implicitly generation 0
collections, unless they are large objects, in which case they go on the large object heap in a
generation 2 collection.
Most objects are reclaimed for garbage collection in generation 0 and do not survive to the next
Generation.

Generation 1. This serves as a buffer between short-lived objects and long-lived objects.

Generation 2. This generation contains long-lived objects. An example of a long-lived object is an


object in a server application that contains static data that is live for the duration of the process.

Execution of C# code:
The .NET Class Library (framework base class library):
Answer: .NET supplies a library of base classes that we can use to implement applications
quickly. We can use them by simply instantiating them & invoking their methods or by inheriting
them through derived classes, thus extending their functionality.
Much of the functionality in the base framework classes resides in the vast namespace called
System. We can use the base classes in the system namespaces for many different tasks
including:
➢ Input/Output Operations.
➢ String handling.
➢ Managing arrays, lists, maps etc.
➢ Accessing files & file systems.
➢ Accessing the registry.
➢ Security.
➢ Windowing.
➢ Windows messages.
➢ Database Management.
➢ Drawing.
➢ Managing errors & exceptions.
➢ Connecting to the Internet.

Difference Between VB.NET and C#

VB.NET C#

It is pronounced as Visual Basic .NET, which


It is pronounced as "C SHARP" language,
is an updated feature and version of Classic
which belongs to the C family.
Visual Basic 6.0.

It is also used to develop various applications It is used to create a variety of application


running on the .NET Framework. that runs on the.NET Framework

Both languages are functionally equal. Both languages are functionally equal.

It is a case insensitive language. For It is a case sensitive language. For example,"


example, "Hello" and "hello" are the same. Hello" and "hello" are different.

VB.NET supports structured and


It supports only structured error handling.
unstructured error handling.

Events are automatically bound. Events are not possible in C#.

Declaration and definition are different in


Declaration and definition are different in both
both.
Whereas, it uses Simple English for defining It uses a simple programming syntax as C,
the variable Java, Python, C++, etc.
Dim x As Integer int x;
Public x As Integer = 10 int x = 10;

Each statement does not end with a Each statement is terminated with a
semicolon. semicolon (;)

The C# Language:
First C# Program:

// Hello World! program


using System;

namespace HelloWorld
{
class Hello
{
static void Main(string[] args)
{
Console.Write("Hello World!");
Console.ReadLine();
}
}
}
Above program consists of the following elements
(i) Namespace
(ii) Comment
(iii) Class
(iV) Main() method
(v) Write() method
(vi) ReadLine() method

Explain different types of data types in C#.


OR
Explain primitive(already defined) and non-primitive(user defined) data types in C#
Answer:

There are two kinds of types in C#: value types and reference types. Variables of value types
directly contain their data whereas variables of reference types store references to their data,
the latter being known as objects. With reference types, it's possible for two variables to
reference the same object and thus possible for operations on one variable to affect the object
referenced by the other variable. With value types, the variables each have their own copy of
the data, and it isn't possible for operations on one to affect the other (except for ref and out
parameter variables).

C#'s value types are further divided into simple types, enum types, struct types, and nullable
value types. C#'s reference types are further divided into class types, interface types, array
types, and delegate types.

C# - Variables:
A variable 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 of the memory required to store data.

Syntax:
<data type> <variable name> = <value>;

The following declares and initializes a variable of an int type.


Example: C# Variable
int num = 100;

Accepting Values from User


The Console class in the System namespace provides a function ReadLine() for accepting input
from the user and store it into a variable.

For example,
int num;
Console.WriteLine(“Enter a value:”);
num = Convert.ToInt32(Console.ReadLine());

The function Convert.ToInt32() converts the data entered by the user to int data type, because
Console.ReadLine() accepts the data in string format.

C# Type Casting
Type casting is when you assign a value of one data type to another type.
In C#, there are two types of casting:
● Implicit Casting (automatically) - converting a smaller type to a larger type size
char -> int -> long -> float -> double

● Explicit Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char

Implicit Casting
Implicit casting is done automatically when passing a smaller size type to a larger size type:
Example
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

Console.WriteLine(myInt); // Outputs 9
Console.WriteLine(myDouble); // Outputs 9

Explicit Casting
Explicit casting must be done manually by placing the type in parentheses in front of the value:
Example
double myDouble = 9.78;
int myInt = (int)myDouble; // Manual casting: double to int

Console.WriteLine(myDouble); // Outputs 9.78


Console.WriteLine(myInt); // Outputs 9

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

Boxing and Unboxing:


Boxing:
Any type, value or reference can be assigned to an object without explicit conversion. When a
compiler finds a value where it needs a reference type, it creates an object ‘box’ into which it
places the value of the value type.
Example: -
int m = 10;
object om = m;
When executed, this code creates a temporary reference _type ‘box’ for the object on heap.
We can also use a C-style cast for boxing.
int m = 10;
object om = (object) m;

Note that the boxing operation creates a copy of the value of the m integer to the object om.
Both the variables exist but the value of om resides on the heap. This means that the values
are independent of each other.
Example
int m =10;
object om = m;
m = 20;
Console.WriteLine(m); // m= 20
Console .WriteLine(om); //om=10

Unboxing:
Unboxing is the process of converting the object type back to the value type. Remember that a
variable can be unboxed only if it has been previously boxed. In contrast to boxing, unboxing is
an explicit operation.

Example:-
int m = 100;
object om = m; //boxing
int n = (int) om; //unboxing

When performing unboxing, C# checks the value type we request is actually stored in the
object under conversion. Only if it is, the value is unboxed.

C# Namespaces:
Namespaces are used in C# to organize and provide a level of separation of codes. They can be
considered as a container which consists of other namespaces, classes, etc.
A namespace can have following types as its members such as Namespaces (Nested Namespace),
Classes, Interfaces, Structures, Delegates

Syntax:
A namespace definition begins with the keyword namespace followed by the
namespace name as follows:

namespace Namespace-Name
{
//Body of namespace
}

Accessing Members of Namespace in C#


Namespace-Name.Member-Name

Example:
using System;
namespace First
{
public class Hello
{
public void sayHello()
{
Console.WriteLine("Hello First Namespace");
}
}
}
namespace Second
{
public class Hello
{
public void sayHello()
{
Console.WriteLine("Hello Second Namespace");
}
}
}
public class TestNamespace
{
public static void Main()
{
First.Hello h1 = new First.Hello();
Second.Hello h2 = new Second.Hello();
h1.sayHello();
h2.sayHello();

}
}

The using Keyword


The using keyword states that the program is using the names in the given namespace.

For example,
We are using the System namespace in our program. The class Console is defined there. We just
write:

Console.WriteLine ("Hello there");

We could have written the fully qualified name as:

System.Console.WriteLine("Hello there");
Alias of Namespace:
using A=System.Console;
class Test
{
static void Main()
{
A.Write("Creation of Alias");
A.ReadKey();
}
}

Here, A is an alias for namespace class Console.


Operators in C#:

C# supports a number of operators that are classified based on the type of operations they
perform.

● Basic Assignment Operator.


● Arithmetic Operators.
● Relational Operators.
● Logical Operators.
● Unary Operators.
● Ternary Operator.
● Bitwise and Bit Shift Operators.
● Compound Assignment Operators.

Arithmetic Operators:

Operator Operator Name Example

+ Addition Operator 6 + 3 evaluates to 9

- Subtraction Operator 10 - 6 evaluates to 4

* Multiplication Operator 4 * 2 evaluates to 8

/ Division Operator 10 / 5 evaluates to 2

Modulo Operator
% 16 % 3 evaluates to 1
(Remainder)
Example:
using System;

namespace Operator
{
class ArithmeticOperator
{
public static void Main(string[] args)
{
double num1 = 14.40, num2 = 4.60, result;
//int num1 = 26, num2 = 4, rem;

// Addition operator
result = num1 + num2;
Console.WriteLine("{0} + {1} = {2}", num1, num2, result);

// Subtraction operator
result = num1 - num2;
Console.WriteLine("{0} - {1} = {2}", num1, num2, result);

// Multiplication operator
result = num1 * num2;
Console.WriteLine("{0} * {1} = {2}", num1, num2, result);

// Division operator
result = num1 / num2;
Console.WriteLine("{0} / {1} = {2}", num1, num2, result);

// Modulo operator
rem = num1 % num2;
Console.WriteLine("{0} % {1} = {2}", num1, num2, rem);
}
}
}

OUTPUT:
14.4 + 4.6 = 19
14.4 - 4.6 = 9.8
14.4 * 4.6 = 66.24
14.4 / 4.6 = 3.1304347826087
26 % 4 = 2
Relational Operators:
Relational operators are used to check the relationship between two operands. If the relationship is
true the result will be true, otherwise it will result in false.Relational operators are used in decision
making and loops.

Operator Operator Name Example

== Equal to 6 == 4 evaluates to false

> Greater than 3 > -1 evaluates to true

< Less than 5 < 3 evaluates to false

>= Greater than or equal to 4 >= 4 evaluates to true

<= Less than or equal to 5 <= 3 evaluates to false

!= Not equal to 10 != 2 evaluates to true

using System;

namespace Operator
{
class RelationalOperator
{
public static void Main(string[] args)
{
bool result;
int num1 = 10, num2 = 20;

result = (num1==num2);
Console.WriteLine("{0} == {1} returns {2}",num1, num2, result);

result = (num1 > num2);


Console.WriteLine("{0} > {1} returns {2}",num1, num2, result);

result = (num1 < num2);


Console.WriteLine("{0} < {1} returns {2}",num1, num2, result);

result = (num1 >= num2);


Console.WriteLine("{0} >= {1} returns {2}",num1, num2, result);

result = (num1 <= num2);


Console.WriteLine("{0} <= {1} returns {2}",num1, num2, result);

result = (num1 != num2);


Console.WriteLine("{0} != {1} returns {2}",num1, num2, result);
}
}
}

OUTPUT:
10 == 20 returns False
10 > 20 returns False
10 < 20 returns True
10 >= 20 returns False
10 <= 20 returns True
10 != 20 returns True

Logical Operators
Logical operators are used to perform logical operations such as and, or. Logical operators operate
on boolean expressions (true and false) and return boolean values. Logical operators are used in
decision making and loops.
Here is how the result is evaluated for logical AND and OR operators.

Operand 1 Operand 2 OR (||) AND (&&)

true true true true

true false true false

false true true false

false false false false

In simple words, the table can be summarized as:


● If one of the operands is true, the OR operator will evaluate it to true.
● If one of the operands is false, the AND operator will evaluate it to false.
using System;
namespace Operator
{
class LogicalOperator
{
public static void Main(string[] args)
{
bool result;
int n1 = 10, n2 = 20;

// OR operator
result = (n1 == n2) || (n1 > 5);
Console.WriteLine(result);

// AND operator
result = (n1 == n2) && (n1 > 5);
Console.WriteLine(result);
}
}
}

Output:
True
False
Difference between for and foreach loop:
for loop foreach loop
1 In case of a for loop control variable of 1 In case of foreach the control variable of
the loop is always be int only. the loop is the same as the type of values
under the array.
2 The for loop executes the statement or 2 The foreach statement repeats a group of
block of statements repeatedly until embedded statements for each element
specified expression evaluates to false. in an array or an object collection.
3 There is need to specify the loop 3 We do not need to specify the loop
bounds(Minimum, Maximum). bounds (Minimum, Maximum).
4 For loop is complex than foreach loop 4 Foreach loop is simple than for loop

5 example: 5 using system;


using system; class class1
class class1 {
{ static void Main()
static void Main() {
{ int j=0;
int j=0; int[] arr=new int[]
for(inti=0; i<=10;i++) {0,3,5,2,5,34,6,3,42,23};
{ foreach(int i in arr)
j=j+1; {
} j=j+1;
Console.ReadLine(); }
} Console.ReadLine();
} }
}
C# Array Types
There are 3 types of arrays in C# programming:
1. Single Dimensional Array
2. Multidimensional Array
3. Jagged Array / variable size array / array of arrays

C# Single Dimensional Array


To create single dimensional array, you need to use square brackets [] after the type.

int[] arr = new int[5]; //creating array

Declaration and Initialization at same time


There are 3 ways to initialize array at the time of declaration.
int[] arr = new int[5]{ 10, 20, 30, 40, 50 };
We can omit the size of array.
int[] arr = new int[]{ 10, 20, 30, 40, 50 };
We can omit the new operator also.
int[] arr = { 10, 20, 30, 40, 50 };

Let's see the example of array where we are declaring and initializing array at the same time.
using System;
public class ArrayExample
{
public static void Main(string[] args)
{
char[] arr = { ‘a’, ‘m’, ‘a’, ‘n’ };//Declaration and Initialization of array

//traversing array
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}

foreach(char n in arr)
{
Console.WriteLine(n);
}
}
}
Output:
10
20
30
40
50

Jagged Array:

In a variable sized array, each row may have different number of columns. It is equivalent to an
array of variable sized one-dimensional arrays. The Length property is used to get the length
of each one-dimensional array. A variable sized array is also known as a jagged array.

A jagged array can be declared and initialized as follows:

datatype[][] arrayname=new datatype[rowsize][];


arrayname[0]=new datatype[]{val1,val2,val3, …};
arrayname[1]=new datatype[]{val1,val2,val3, …};
arrayname[2]=new datatype[]{val1,val2,val3, …};

arrayname[rowsize-1]=new datatype[]{val1,val2,val3, …};

Example:
class numadd
{
public static void Main()
{
int[][] x=new int[4][];
x[0]=new int[2]{5,13};
x[1]=new int[3]{7,8,11};
x[2]=new int[4]{2,3,4,5};
x[3]=new int[1]{9};
for(int i=0;i<4;i++)
{
for(int j=0;j<x[i].Length;j++)
{
Console.Write(x[i][j]+"\t");
}
Console.Write("\n");
}
}

What is flow control? Explain break and continue statements:


Answer:
Flow Control(Looping and Branching):
In each case, program execution has proceeded from one line to the next in top-to-bottom
order, missing nothing.

This topic describes two methods for controlling program flow — that is, the order of
execution of lines of C# code: branching and looping. Branching executes code
conditionally, depending on the outcome of an evaluation, such as ‘‘only execute this code if
the variable myVal is less than 10.’’ Looping repeatedly executes the same statements, either
a certain number of times or until a test condition has been reached.
Both of these techniques involve the use of Boolean logic.

Break statement:
When the break statement is encountered inside a loop, the loop is immediately terminated and
program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement.
while(test-condition)
{
---
---
if(condition)
break;
---
---
}
stat-x;
---
---

Continue statement: Continue statement tells the compiler “SKIP THE FOLLOWING STATEMENT(S)
AND CONTINUE WITH THE NEXT ITERATION”. Causes the current loop cycle to end immediately
(execution continues with the next loop cycle).
Example:
while(test-condition)
{
---
---
if(condition)
continue;
---
--- skip
}

Example:
class Program
{
static void Main(string[] args)
{
int i;
for (i = 0; i <= 10; i++)
{
if (i == 5)
continue;

if (i == 8)
break;

Console.WriteLine("value is" +i);


}
Console.ReadLine();
}
}

When the above code is compiled and executed, it produces the following result −
value is: 0
value is: 1
value is: 2
value is: 3
value is: 4
value is: 6
value is: 7

Write a short note on object based manipulation in C#.


Answer:

Object Based Manipulation in C#:


.NET is object oriented to the core. In fact, even ordinary variables are really full-fledged
objects in disguise. This means that common data types have the built-in smart to handle
basic operations (such as counting the number of characters in a string). Even better, it
means you can manipulate strings, dates, and numbers in the same way in C# or VB
language.

As an example, every type in the .NET class library includes a ToString() method. The default
implementation of ‘this’ method returns the class name.

The following code snippet demonstrates how to use the ToString() method with an integer:

string VMyString;
int vMyInteger=100;
vMyString=vMyInteger.ToString();

Method Parameters / arguments in C#:


There are four types of parameters in C#:

params: In C#, params is a keyword which is used to specify a parameter that takes a
variable number of arguments. It is useful when we don't know the number of arguments
prior. Only one Params keyword is allowed and no additional Params will be allowed in
function declaration after a params keyword. The length of params will be zero if no
arguments will be passed.

specifies that this parameter may take a variable number of arguments.

ref: The ref keyword is used to pass an argument as a reference. This means that when
the value of that parameter is changed in the method, it gets reflected in the calling
method. An argument that is passed using a ref keyword must be initialized in the calling
method before it is passed to the called method..

out: The out keyword is also used to pass an argument like ref keyword, but the
argument can be passed without assigning any value to it. An argument that is passed
using an out keyword must be initialized in the called method before it returns back to
calling method.
Ref parameter:

using System;

namespace CalculatorApplication {
class NumberManipulator {
public void swap(ref int x, ref int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
}

static void Main(string[] args)


{
NumberManipulator n = new NumberManipulator();

/* local variable definition */


int a = 100;
int b = 200;

Console.WriteLine("Before swap, value of a : {0}", a);


Console.WriteLine("Before swap, value of b : {0}", b);

/* calling a function to swap the values */


n.swap(ref a, ref b);

Console.WriteLine("After swap, value of a : {0}", a);


Console.WriteLine("After swap, value of b : {0}", b);

Console.ReadLine();
}
}
}
Output
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

Out Parameter:
namespace MyNamespace
{
class Program
{
static void Main(string[] args)
{
int x, y;
Multiplication(out x, out y); // Function call

Console.WriteLine("Variables Values: {0} {1}", x, y);


Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
public static void Multiplication(out int a, out int b)
{
a = 10;
a *= a;

b = 200;
}
}
}
Difference between Ref and Out keywords
REF KEYWORD OUT KEYWORD

It is necessary the parameters should initialize It is not necessary to initialize


before it passed to ref. parameters before it passed to out.

It is necessary to initialize the value of


It is not necessary to initialize the value of a
a parameter before returning to the
parameter before returning to the calling method.
calling method.

The passing of value through the ref parameter is The declaration of parameters through
useful when the called method also needs to the out parameter is useful when a
change the value of the passed parameter. method returns multiple values.

When ref keyword is used the data may pass in When out keyword is used the data
bi-directional. only passed in unidirectional.
Params Parameter:
public class MyClass
{
public static void UseParams(params int[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}

public static void UseParams2(params object[] list)


{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}

static void Main()


{
// You can send a comma-separated list of arguments of the specified type
UseParams(1, 2, 3, 8,7,744,55,66,11,7);
UseParams2(1, 'a', "test");

// A params parameter accepts zero or more arguments.


UseParams2();

// An array argument can be passed, as long as the array type matches the parameter type of the
method being called.
int[] myIntArray = { 5, 6, 7, 8, 9 };
UseParams(myIntArray);

object[] myObjArray = { 2, 'b', "test", "again" };


UseParams2(myObjArray);

// The following call causes a compiler error because the object


// array cannot be converted into an integer array.
//UseParams(myObjArray);
}
}
/*
Output:
1234
1 a test

56789
2 b test again
*/

Explain method overriding with example


Method overriding in C# is achieved through inheritance.
If a class is inherited by a derived class, then the derived class can override the base class method.
This concept is termed as Method Overriding.
Method Overriding is implemented in C# using the keywords virtual and override. The base class
method that has to be overridden must be marked as virtual or abstract (if the base class is an abstract
class).

The derived class method that overrides the base class method should be marked with the keyword
override.

Example:
using System;
class A
{
public void Test()
{
Console.WriteLine("A::Test()");
}
}
class B : A
{
Public override void Test()
{
Console.WriteLine("B::Test()");
}
}
class C : B
{
public override void Test() { Console.WriteLine("C::Test()"); }
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
C c = new C();
a.Test(); // output --> "A::Test()"
b.Test(); // output --> "B::Test()"
c.Test(); // output --> "C::Test()"
a = new B();
a.Test(); // output --> "B::Test()"
b = new C();
b.Test(); // output --> "C::Test()"
Console.ReadKey();
}
}
Difference between overloading and overriding:

Overloading Overriding

Overloading happens at compile-time Overriding happens at runtime:

Static methods can be overloaded which Static methods cannot be overridden, even if
means a class can have more than one static you declare the same static method in child
method of the same name. class it has nothing to do with the same
method of parent class.

Overloading is being done in the same class For overriding base and child classes are
required

Static binding is being used for overloaded Dynamic binding is being used for
methods overridden/overriding methods.

Private and final methods can be overloaded. It Private and final methods cannot be
means a class can have more than one overridden. It means a child class cannot
private/final methods of same name override the private/final methods of their base
class.

Return type of method does not matter in case However in case of method overriding the
of method overloading, it can be the same or overriding method can have more specific
different. return type.
What are sealed classes and sealed methods? Why are they used?
This is a method that is declared with the keyword sealed and is always used with an override
keyword. Such method provides a complete implementation to its base class virtual method using the
override keyword. Prevent overriding a method of a class. Derived classes will not be able to
override further this method as it is sealed for overriding.

Characteristics
● A method cannot be defined as sealed unless that method is an override of a method in its base
class.
● A sealed method cannot be overridden further.
● Sealed methods are useful to avoid problems caused by overriding the existing functionality.
● It prevents the user from changing the internal functionality of a class.

Example:
using System;
class A
{
public virtual void F()
{
Console.WriteLine("A.F");
}
public virtual void G()
{
Console.WriteLine("A.G");
}
}
class B: A
{
sealed override public void F()
{
Console.WriteLine("B.F");
}
override public void G()
{
Console.WriteLine("B.G");
}
}
class C: B
{
override public void G()
{
Console.WriteLine("C.G");
}
}
The class B provides two override methods: an F method that has the sealed modifier and a G
method that does not. B's use of the sealed modifier prevents C from further overriding F.

Sealed Class:
A sealed class cannot be inherited. Means, no class can be derived from a sealed
class. To make a class sealed, we use the keyword sealed in class declaration. For
example, if we seal class A as below source code then class B cannot be derived from
it. One question arises immediately that can we create object of sealed class in C#
program? Answer is, of course we can create objects of a sealed class. Purpose of
sealed class is only to prevent a class to be inherited.

It is not permitted to use the abstract modifier with a sealed class.

Example:
using System;
sealed class MyClass
{
public int x;
public int y;
}
class MainClass
{
public static void Main()
{
MyClass mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
Abstract Method
A method which is declared abstract and has no body is called an abstract method. It can be
declared inside the abstract class only. Its implementation must be provided by derived classes.
For example:
public abstract void draw();

Note: An abstract method in C# is internally a virtual method so it can be overridden by the derived
class.
Abstract Class:
In C#, abstract class is a class which is declared abstract. It can have abstract and non-abstract
methods. It cannot be instantiated. Its implementation must be provided by derived classes. Here, the
derived class is forced to provide the implementation of all the abstract methods.

You can derive both abstract and non-abstract classes from an abstract base class. Interfaces are
implicitly abstract.

using System;
public abstract class Shape
{
public abstract void draw();
}
public class Rectangle : Shape
{
public override void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Shape
{
public override void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestAbstract
{
public static void Main()
{
Shape s;
s = new Rectangle();
s.draw();
s = new Circle();
s.draw();
}
}
Output:
drawing ractangle...
drawing circle...

C# Interface:
Interface in C# is a blueprint of a class. It is like an abstract class because all the methods which are
declared inside the interface are abstract methods. It cannot have a method body and cannot be
instantiated.
It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve full
abstraction because it cannot have a method body.
Its implementation must be provided by class or struct. The class or struct which implements the
interface, must provide the implementation of all the methods declared inside the interface.

using System;
public interface Drawable
{
void draw();
}
public class Rectangle : Drawable
{
public void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Drawable
{
public void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestInterface
{
public static void Main()
{
Drawable d;
d = new Rectangle();
d.draw();
d = new Circle();
d.draw();
}
}
Output:
drawing ractangle...
drawing circle...

Switch statement:
Use the switch statement to select one of many code blocks to be executed. The switch statement is
an alternative to if else statement.
Syntax:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
This is how it works:
● The switch expression is evaluated once.
● The switch expression is of integer type such as int, char, byte, or short, or of an enumeration
type, or of string type.
● The value of the expression is compared with the values of each case label.
● If there is a match, the associated block of code is executed.
● break causes the termination of the switch statement.
● default marks the block that would get executed if the switch expression does not
match any case labels.

Example:
using System;

namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int day= 4;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
}
}
}
}

fall through in switch:


Every case must have a break, continue, goto, return or throw at its end. In C# we cannot have cases
with statements fall through to the following case.
C# program that has fall-through error

using System;

class Program
{
static void Main()
{
int value = 0;
// ... Every switch statement must be terminated.
switch (value)
{
case 0:
Console.WriteLine("Zero");
case 1:
Console.WriteLine("One");
break;
}
}
}

Output
Error 1
Control cannot fall through from one case label ('case 0:') to another.

in C#:
In C#, collection represents a group of objects. By the help of collections, we can perform various
operations on objects such as insert, delete, search, modify etc.
The System.Collections namespace has following classes:

CLASS
DESCRIPTION
NAME

It is a dynamic array means the size of the array is not fixed, it can increase
ArrayList
and decrease at runtime.

It represents a collection of key-and-value pairs that are organized based


on the hash code of the key.
Hashtable
a[0]=10;
It represents a first-in, first out collection of objects. It is used when you
Queue
need a first-in, first-out access of items.

It is a linear data structure. It follows the LIFO(Last In, First Out) pattern for
Stack
Input/output.

ArrayList Collection:
The ArrayList in C# is a collection class that works like an array but provides the facilities such as
dynamic resizing, adding and deleting elements from the middle of a collection. It implements the
System.Collections.IList interface using an array whose size is dynamically increased as required.

Methods and properties provided by the ArrayList collection class in C#.


● Add(): This method is used to add an object to the end of the collection.
● Remove(): This method is used to remove the first occurrence of a specific object from the
collection.
● RemoveAt(int index): This method takes the index position of the elements and removes
that element from the collection.
● Insert(int index, Object): This method is used to insert an element into the collection at the
specified index.

Properties:

● Capacity: This property gives you the capacity of the collection means how many
elements you can insert into the collection.
● Count: This property gives you the number of elements present in a collection.

ArrayList name = new ArrayList();

using System;
using System.Collections;
namespace ArrayListCollection
{
class Program
{
static void Main(string[] args)
{
//Creating ArrayList collection using default constructor
ArrayList al = new ArrayList();

Console.WriteLine("Initial Capacity: " + al.Capacity);


al.Add(10);
Console.WriteLine("Capacity after adding first item: " + al.Capacity);
al.Add("hello");
al.Add(true);
al.Add(3.14f);
Console.WriteLine("Capacity after adding fourth item: " + al.Capacity);
al.Add('A');
Console.WriteLine("Capacity after adding 5th element: " + al.Capacity);

//Printing the ArrayList elements using for loop


for (int i = 0; i < al.Count; i++)
{
Console.Write(al[i] + " ");
};

//Removing the values from the middle of the array list


//here we are removing by value
al.Remove(true);
//You can also remove element by using index position
// al.RemoveAt(2);
//Printing the ArrayList elements using foreach loop after
// removing an element from the collection
foreach (object obj in al)
{
Console.Write(obj + " ");
}
Console.WriteLine();
//inserting values into the middle of the array list collection
al.Insert(2, false);
// Printing the values of the collection using foreach loop after
// inserting an element into the middle of the collection
foreach (object obj in al)
{
Console.Write(obj + " ");
}
Console.WriteLine();
// creating new ArrayList collection by passing the old
// array list as parameter
ArrayList coll = new ArrayList(al);
Console.WriteLine("Initial capacity of new array list collection:" + coll.Capacity);
// Printing the values of the new array list collection using foreach loop
foreach (object obj in coll)
{
Console.Write(obj + " ");
}
Console.ReadKey();
}
}
}

Output:
Initial Capacity: 0
Capacity after adding first item: 4
Capacity after adding fourth item: 4
Capacity after adding 5th element: 8
10 hello True 3.14 A
10 hello 3.14 A
10 hello False 3.14 A
Initial capacity of new array list collection:5
10 hello False 3.14 A
You have applied to the University Portal for FY B. Sc (IT) admission & selected VPMs RZ Shah
College Mulund. Now submit online application form to our college, if you have not yet applied on
www.vpmrzshahcollege.edu.in

How to create and use property in C#.


In C# properties are nothing but natural extension of data fields. They are usually known as
'smart fields' in C# community. We know that data encapsulation and hiding are the two
fundamental characteristics of any object-oriented programming language.
In C#, data encapsulation is possible through either classes or structures. By using various
access modifiers like private, public, protected, internal etc it is possible to control the
accessibility of the class members.

Usually inside a class, we declare a data field as private and will provide a set of public SET
and GET methods to access the data fields.
In C#, properties are defined using the property declaration syntax. The general form of
declaring a property is as follows.

<acces_modifier> <return_type> <property_name>


{
get
{
return var;
}
set
{
var = value;
}
}

Example:
using System;
class MyClass
{
private int x;
public int A // A is name of the property
{
set
{
x = value; // value is a keyword
}
get
{
return x;;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.X = 10;
int xVal = mc.X;
Console.WriteLine(xVal);//Displays 10
}
}

What is an assembly? Explain different components of assembly.


Assembly:
Microsoft .Net Assembly is a logical unit of code, that contains code which the Common Language
Runtime (CLR) executes. It is the smallest unit of deployment of a .net application. It includes both
executable application files that you can run directly from Windows without the need for any other
programs (.exe files), and libraries (.dll files) for use by other applications. All the .NET assemblies

contain the definition of types, versioning information.


Components of Assembly
Manifest:
It describes the assembly itself. The manifest file contains all the metadata needed to specify the
assembly's version requirements, security identity, and all metadata needed to define the scope of the
assembly and resolve references to resources and classes.

Type Metadata:
Metadata describes the contents in an assembly. In addition to containing MSIL, assemblies
also include meta information (that is, information about the information contained in the
assembly, also known as metadata ) and optional resources (additional data used by the MSIL,
such as sound files and pictures). The meta information enables assemblies to be fully
self-descriptive. You need no other information to use an assembly, meaning you avoid
situations such as failing to add required data to the system registry and so on, which was often
a problem when developing with other platforms.

MSIL:
It contains Intermediate language code.
Resources:
It contains bitmaps, icons, audios and other types of resources.
There are two types of assemblies: private and shared. A private assembly can be used by
only a single application. A shared assembly, on the other hand, can be used by all applications
located on the same server.

Shared assemblies are located in the Global Assembly Cache (GAC). For example, the
System.Web.dll assembly and all the other assemblies included with the .NET Framework are
located in the Global Assembly Cache.

Private Assembly Public Assembly

Private assembly can be used by only one Public assembly can be used by multiple
application. applications.

Private assembly will be stored in the specific Public assembly is stored in GAC (Global
application's directory or sub-directory/root Assembly Cache).
directory.

There is no other name for private assembly. Public assembly is also termed as shared
assembly.

Strong name is not required for private assembly. Strong name has to be created for public
assembly.

Private assembly doesn't have any version Public assembly should strictly enforce version
constraint. constraint.

The dll or exe which is sole property of one It is a dll which can be used by multiple
application only. applications at a time.

What is GAC(Global Assembly Cache )?


Any computer where the CLR is installed has a global assembly cache. Global Assembly Cache
stores assemblies designated to be shared by multiple applications. It's a method to store DLLs in
such a way that it can be accessible globally without worrying about any conflicts.
gacutil.exe

Note:
The Global Assembly Cache is located physically in your computer's \WINDOWS\Assembly folder.
There is a separate copy of every assembly in your
C:\Windows\Microsoft.NET\Framework\v4.0.30319 folder. The first set of assemblies is used at
runtime and the second set is used at compile time.

What is meant by Managed and Unmanaged code?


Answer:
The code that is managed by the CLR is called Managed code. This code runs inside the CLR. Hence,
it is necessary to install the .Net framework in order to execute the managed code. CLR manages the
memory through garbage collection and also uses the other features like Code Access
Security(CAS-CLR’s mechanism for maintaining security based on the identity of code.) and CTS for
efficient management of the code.

Unmanaged code is any code that does not depend on CLR for execution. It means it is developed by
any other language independent of .Net framework. It uses its own runtime environment for compiling
and execution.

Though it is not running inside the CLR, the unmanaged code will work properly if all the other
parameters are correctly followed.

Hiding methods:
To hide base class methods in derived classes we can declare derived class methods with new
keyword. To use new keyword, we need to write the code like as shown below
Example:-
class SampleA
{
public void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public new void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
a.Show();
b.Show();
a = new SampleB();
a.Show();
Console.ReadLine();
}
}

Creating and using delegates involve four steps-


A delegate is a type that represents a method with a specific signature and return type. The
declaration of a delegate looks exactly like the declaration of a method, except with the
keyword delegate in front of it.

Types of Delegate: Unicast (Single cast) Delegate Multicast Delegate


1. Delegate declaration.
-> public delegate void mydelegate(int a, int b);
2. Delegate methods definition.
public void sum(int a, int b)
{
Console.WriteLine("(100 + 40) = {0}", a + b);
}
public void mul(int a, int b)
{
Console.WriteLine("(100 * 40) = {0}", a * b);
}

3. Create an instance of Delegate.


mydelegate del_obj1 = new mydelegate(obj.sum);
del_obj1(100,40); //Invoke Delegate.
mydelegate del_obj2 = new mydelegate addnum(obj.mul);
del_obj1(100,40); //Invoke Delegate.

class DelegateEx
{
// Declaring the delegates
public delegate void addnum(int a, int b);
public delegate void subnum(int a, int b);
// Defining delegate methods
public void sum(int a, int b)
{
Console.WriteLine("(100 + 40) = {0}", a + b);
}

public void subtract(int a, int b)


{
Console.WriteLine("(100 - 60) = {0}", a - b);
}

public static void Main(String []args)


{

// creating object "obj" of class "DelegateEx "


DelegateEx obj = new DelegateEx ();

// instantiating the delegates


addnum del_obj1 = new addnum(obj.sum);
subnum del_obj2 = new subnum(obj.subtract);

// pass the values to the methods by delegate object


del_obj1(100, 40); // or del_obj1.Invoke(100, 40);
del_obj2(100, 60); // or del_obj2.Invoke(100, 60);
}
}

Multicast Delegate:
Multicast Delegate is an extension of normal delegates. It combines more than one method at a
single moment of time.

1. In Multicasting, Delegates can be combined and when you call a delegate, a whole list of
methods is called.
2. void is used as return type
3. out parameter is not allowed as arguments
4. All methods are called in FIFO (First in First Out) order.
5. + or += Operator is used for adding methods to delegates.
6. – or -= Operator is used for removing methods from the delegates list

public delegate void MyDelegate(); // Declarations of delegate


class A
public void Show() // Definition of delegate method
{
Console.WriteLine (“New Delhi”);
}
public void Display() // Definition of delegate method
{
Console.WriteLine (“New York”);
}
}
class Xyz
{
public static void Main()
{
Abc a1=new Abc();
MyDelegate m1=new MyDelegate(a1.Show);
MyDelegate m2=new MyDelegate(a1.Display);

m1=m1+m2+m1+m2-m1;
m1();

Console.Read();
}
}
OUTPUT:
New Delhi
New York
New York
1. using System;
2. delegate int Calculator(int n);//declaring delegate
3.
4. public class DelegateExample
5. {
6. static int number = 100;
7. public static int add(int n)
8. {
9. number = number + n;
10. return number;
11. }
12. public static int mul(int n)
13. {
14. number = number * n;
15. return number;
16. }
17. public static int getNumber()
18. {
19. return number;
20. }
21. public static void Main(string[] args)
22. {
23. Calculator c1 = new Calculator(add);//instantiating delegate
24. Calculator c2 = new Calculator(mul);
25. c1(20);//calling method using delegate
26. Console.WriteLine("After c1 delegate, Number is: " + getNumber());
27. c2(3);
28. Console.WriteLine("After c2 delegate, Number is: " + getNumber());
29.
30. }
31.}

You might also like