1 Explain General Structure of Csharp Program.?

You might also like

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

RTM Nagpur University

Solutions Set
C# and DotNet

1 Explain General Structure of CSharp Program.?


A C# program consists of the following parts −

Namespace declaration
A class
Class methods
Class attributes
A Main method
Statements and Expressions
Comments
Let us look at a simple code that prints the words "Hello World" −

Live Demo
using System;

namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
When this code is compiled and executed, it produces the following result −

Hello World
Let us look at the various parts of the given program −

The first line of the program using System; - the using keyword is used to include the System
namespace in the program. A program generally has multiple using statements.

The next line has the namespace declaration. A namespace is a collection of classes. The
HelloWorldApplication namespace contains the class HelloWorld.

The next line has a class declaration, the class HelloWorld contains the data and method
definitions that your program uses. Classes generally contain multiple methods. Methods define
the behavior of the class. However, the HelloWorld class has only one method Main.

The next line defines the Main method, which is the entry point for all C# programs. The Main
method states what the class does when executed.
The next line /*...*/ is ignored by the compiler and it is put to add comments in the program.

The Main method specifies its behavior with the statement Console.WriteLine("Hello World");

WriteLine is a method of the Console class defined in the System namespace. This statement
causes the message "Hello, World!" to be displayed on the screen.

The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a
key press and it prevents the screen from running and closing quickly when the program is
launched from Visual Studio .NET.

2 Write note on Array type , Delegate type?

Array type:
A C# program consists of the following parts −

Namespace declaration
A class
Class methods
Class attributes
A Main method
Statements and Expressions
Comments
Let us look at a simple code that prints the words "Hello World" −

Live Demo
using System;

namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
When this code is compiled and executed, it produces the following result −

Hello World
Let us look at the various parts of the given program −

The first line of the program using System; - the using keyword is used to include the System
namespace in the program. A program generally has multiple using statements.
The next line has the namespace declaration. A namespace is a collection of classes. The
HelloWorldApplication namespace contains the class HelloWorld.

The next line has a class declaration, the class HelloWorld contains the data and method
definitions that your program uses. Classes generally contain multiple methods. Methods define
the behavior of the class. However, the HelloWorld class has only one method Main.

The next line defines the Main method, which is the entry point for all C# programs. The Main
method states what the class does when executed.

The next line /*...*/ is ignored by the compiler and it is put to add comments in the program.

The Main method specifies its behavior with the statement Console.WriteLine("Hello World");

WriteLine is a method of the Console class defined in the System namespace. This statement
causes the message "Hello, World!" to be displayed on the screen.

The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a
key press and it prevents the screen from running and closing quickly when the program is
launched from Visual Studio .NET.

Delegate type:
XX obj = new XX();
obj.MyEvent += new MyDelegate(obj.Add);
obj.MyEvent += new MyDelegate(obj.Subtract);
obj.RaiseEvent(20, 10);
Console.ReadLine();
}
}
}

3 Explain default constructor? Explain its concept with suitable example?


If you don’t provide a constructor for your class, C# creates one by default that instantiates the
object and sets member variables to the default values as listed in the Default Values Table.
Constructor without any parameters is called a default constructor. In other words, this type of
constructor does not take parameters. The drawback of a default constructor is that every
instance of the class will be initialized to the same values and it is not possible to initialize each
instance of the class to different values.

The default constructor initializes:

All numeric fields in the class to zero.


All string and object fields to null.
Example 1:

filter_none
edit
play_arrow

brightness_4
// C# Program to illustrate the use
// of Default Constructor
using System;

namespace GFG {

class multiplication
{
int a, b;

// default Constructor
public multiplication()
{
a = 10;
b = 5;
}

// Main Method
public static void Main() {

// an object is created,
// constructor is called
multiplication obj = new multiplication();

Console.WriteLine(obj.a);
Console.WriteLine(obj.b);

Console.WriteLine("The result of multiplication is: "


+(obj.a * obj.b));
}

}
}
Output:

10
5
The result of multiplication is: 50
Example 2: In this example, the class Person does not have any constructors, in which case, a
default constructor is automatically provided and the fields are initialized to their default values.

filter_none
edit
play_arrow

brightness_4
// C# Program to illustrate the use
// of Default Constructor
using System;

public class Person


{
public int age;
public string name;
}

// Driver Class
class TestPerson {

// Main Method
static void Main() {

// object creation
Person pers = new Person();

Console.WriteLine("Name: {0}, Age: {1}", pers.name, pers.age);

}
}
Output:

Name: , Age: 0
Note: The output is so because a string is assigned to null by default and integers to 0.

4 Explain logical and relational operators with example?

In c#, Logical Operators are used to perform the logical operation between two operands like
AND, OR and NOT based on our requirements. The Logical Operators will always work with
Boolean expressions (true or false) and return Boolean values.

The operands in logical operators must always contain only Boolean values otherwise Logical
Operators will throw an error.
Following table lists the different type of operators available in c# relational operators.

Operator Name Description Example (a = true, b = false)


&& Logical AND It return true if both operands are non zero. a && b (false)
|| Logical OR It returns true if any one operand become a non zero. a || b (true)
! Logical NOT It return the reverse of logical state that means if both operands are non
zero then it will return false. !(a && b) (true)
If we use Logical AND, OR operators in c# applications, those will return the result like as
shown below for different inputs.

Operand1 Operand2 AND OR


true true true true
true false false true
false true false true
false false false false
If you observe above table, if any one operand value become false, then the logical AND
operator will return false, same way the logical OR operator will return true, if any one operand
value become true.

In case if we use Logical NOT operator in our c# applications, it will return the results like as
shown below for different inputs.

Operand NOT
true false
false true
If you observe above table, the Logical NOT operator will always return the reverse value of
operand like if operand value true, then the Logical NOT operator will return false and vice
versa.

C# Logical Operators Example


Following is the example of using the Logical Operators in c# programming language.

using System;
namespace Tutlane

class Program

static void Main(string[] args)

int x = 15, y = 10;

bool a = true, result;

// AND operator

result = (x <= y) && (x > 10);

Console.WriteLine("AND Operator: " + result);

// OR operator

result = (x >= y) || (x < 5);

Console.WriteLine("OR Operator: " + result);

//NOT operator

result = !a;

Console.WriteLine("NOT Operator: " + result);

Console.WriteLine("Press Enter Key to Exit..");

Console.ReadLine();

}
If you observe above code, we used a logical operators (AND, OR, NOT) to perform different
operations on defined operands.
Following table shows all the relational operators supported by C#. Assume variable A holds 10
and variable B holds 20, then −

Operator Description Example

== Checks if the values of two operands (A ==


are equal or not, if yes then condition B) is not
becomes true. true.

!= Checks if the values of two operands (A != B)


are equal or not, if values are not equal is true.
then condition becomes true.

> Checks if the value of left operand is (A > B)


greater than the value of right operand, is not
if yes then condition becomes true. true.

< Checks if the value of left operand is (A < B)


less than the value of right operand, if is true.
yes then condition becomes true.

>= Checks if the value of left operand is (A >=


greater than or equal to the value of B) is not
right operand, if yes then condition true.
becomes true.

<= Checks if the value of left operand is (A <=


less than or equal to the value of right B) is
operand, if yes then condition becomes true.
true.

Example
The following example demonstrates all the relational operators available in C# −
Live Demo

using System;

class Program {
static void Main(string[] args) {
int a = 21;
int b = 10;
if (a == b) {
Console.WriteLine("Line 1 - a is equal to b");
} else {
Console.WriteLine("Line 1 - a is not equal to b");
}

if (a < b) {
Console.WriteLine("Line 2 - a is less than b");
} else {
Console.WriteLine("Line 2 - a is not less than b");
}

if (a > b) {
Console.WriteLine("Line 3 - a is greater than b");
} else {
Console.WriteLine("Line 3 - a is not greater than b");
}

/* Lets change value of a and b */


a = 5;
b = 20;

if (a <= b) {
Console.WriteLine("Line 4 - a is either less than or equal to b");
}

if (b >= a) {
Console.WriteLine("Line 5-b is either greater than or equal to b");
}
}
}
When the above code is compiled and executed, it produces the following result −

Line 1 - a is not equal to b


Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b

5 What is creation of object in csharp? Explain accessing class members with example?
Object:
Object, in C#, is an instance of a class that is created dynamically. Object is also a keyword that
is an alias for the predefined type System.Object in the .NET framework.
The unified type system of C# allows objects to be defined. These can be user-defined, reference
or value type, but they all inherit directly or indirectly from System.Object. This inheritance is
implicit so that the type of the object need not be declared with System.Object as the base class.
In general, object type is useful where there is a requirement to build generic routines. Because
values of any type can be assigned to variables of object type, object type is used mostly in
designing classes that handle objects of any type that allow code to be reused. The non-generic
collection classes in the .NET framework library, such as ArrayList, Queue, etc., use object type
to define various collections.
An object is also known as instance.

Accessing class members:


By using Public Method

We can access a private variable in a different class by putting that variable with in a Public
method and calling that method from another class by creating object of that class.

Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class PrivateVariable
{
private int i = 10; //Declaring and initializing a private variable
public void DisplayVariable()
{
Console.Write("The Value of Private Variable=" + i); //Accessing Private variable with
in a public methode
}
}
class DisplayPrivateVariable
{
static void Main()
{
PrivateVariable objPrivateVariable = new PrivateVariable();
objPrivateVariable.DisplayVariable(); //Calling the public method
}
}
}
By Using Inner class

By using inner class also we can access a private variable of a class in another class. For better
understanding have look at the example.

Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class PrivateVariable2
{
class Outerclass
{
private int i = 10;
private int j = 20;
class Innerclass
{
static void Main()
{
Outerclass objouter = new Outerclass();
int Result = objouter.i + objouter.j;
Console.Write("Sum=" + Result);
Console.ReadLine();
}
}
}
}
}
By Using Properties

By using properties also we can do the same work as previous.


Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Employee
{
private int _EmpID = 1001;
private string _EmpName;
public int EmpID
{
get
{
return _EmpID;
}
}
public string EmpName
{
get
{
return _EmpName;
}
set
{
_EmpName = "Smith";
}
}
}
class AcessEmployee
{
static void Main()
{
Employee objEmployee = new Employee();
Console.WriteLine("Employee ID: " + objEmployee.EmpID);
Console.WriteLine("Employee old Name: " + objEmployee.EmpName);
objEmployee.EmpName = "Dyne Smith";
Console.WriteLine("Employee New Name: " + objEmployee.EmpName);
Console.ReadLine();
}
}
}

6. Explain the concept of method overloading along with example?


C# | Method Overloading
Method Overloading is the common way of implementing polymorphism. It is the ability to
redefine a function in more than one form. A user can implement function overloading by
defining two or more functions in a class sharing the same name. C# can distinguish the methods
with different method signatures. i.e. the methods can have the same name but with different
parameters list (i.e. the number of the parameters, order of the parameters, and data types of the
parameters) within the same class.

Overloaded methods are differentiated based on the number and type of the parameters passed as
arguments to the methods.
You can not define more than one method with the same name, Order and the type of the
arguments. It would be compiler error.
The compiler does not consider the return type while differentiating the overloaded method. But
you cannot declare two methods with the same signature and different return type. It will throw a
compile-time error. If both methods have the same parameter types, but different return type,
then it is not possible.
Why do we need Method Overloading ??

If we need to do the same kind of the operation in different ways i.e. for different inputs. In the
example described below, we are doing the addition operation for different inputs. It is hard to
find many different meaningful names for single action.

Different ways of doing overloading methods-


Method overloading can be done by changing:

The number of parameters in two methods.


The data types of the parameters of methods.
The Order of the parameters of methods.
By changing the Number of Parameters

filter_none
edit
play_arrow

brightness_4
// C# program to demonstrate the function
// overloading by changing the Number
// of parameters
using System;
class GFG {

// adding two integer values.


public int Add(int a, int b)
{
int sum = a + b;
return sum;
}

// adding three integer values.


public int Add(int a, int b, int c)
{
int sum = a + b + c;
return sum;
}

// Main Method
public static void Main(String[] args)
{

// Creating Object
GFG ob = new GFG();

int sum1 = ob.Add(1, 2);


Console.WriteLine("sum of the two "
+ "integer value : " + sum1);

int sum2 = ob.Add(1, 2, 3);


Console.WriteLine("sum of the three "
+ "integer value : " + sum2);
}
}
Output:
sum of the two integer value : 3
sum of the three integer value : 6
By changing the Data types of the parameters

filter_none
edit
play_arrow

brightness_4
// C# program to demonstrate the function
// overloading by changing the Data types
// of the parameters
using System;
class GFG {

// adding three integer values.


public int Add(int a, int b, int c)
{
int sum = a + b + c;
return sum;
}

// adding three double values.


public double Add(double a,
double b, double c)
{
double sum = a + b + c;
return sum;
}

// Main Method
public static void Main(String[] args)
{

// Creating Object
GFG ob = new GFG();

int sum2 = ob.Add(1, 2, 3);


Console.WriteLine("sum of the three "
+ "integer value : " + sum2);
double sum3 = ob.Add(1.0, 2.0, 3.0);
Console.WriteLine("sum of the three "
+ "double value : " + sum3);
}
}
Output:
sum of the three integer value : 6
sum of the three double value : 6
By changing the Order of the parameters

filter_none
edit
play_arrow

brightness_4
// C# program to demonstrate the function
// overloading by changing the
// Order of the parameters
using System;
class GFG {

// Method
public void Identity(String name, int id)
{

Console.WriteLine("Name : " + name + ", "


+ "Id : " + id);
}

// Method
public void Identity(int id, String name)
{

Console.WriteLine("Name : " + name + ", "


+ "Id : " + id);
}

// Main Method
public static void Main(String[] args)
{

// Creating Object
GFG obj = new GFG();

obj.Identity("Akku", 1);
obj.Identity("Abby", 2);
}
}
Output:
Name : Akku, Id : 1
Name : Abby, Id : 2
What happens when method signature is same and the return type is different?

The compiler will give error as the return value alone is not sufficient for the compiler to figure
out which function it has to call. Only if both methods have different parameter types (so, they
have the different signature), then Method overloading is possible.
Example:

filter_none
edit
play_arrow

brightness_4
// C# program to show error when method signature
// is the same and the return type is different.
using System;
class GFG {
// adding two integer value.
public int Add(int a, int b)
{

int sum = a + b;
return sum;
}

// adding three integer value.


public double Add(int a, int b)
{
double sum = a + b + 0.0;
return sum;
}

// Main Method
public static void Main(String[] args)
{

// Creating Object
GFG ob = new GFG();

int sum1 = ob.Add(1, 2);


Console.WriteLine("sum of the two "
+ "integer value :" + sum1);

int sum2 = ob.Add(1, 2);


Console.WriteLine("sum of the three "
+ "integer value :" + sum2);
}
}
Compile Time Error:

prog.cs(15,19): error CS0111: A member `GFG.Add(int, int)’ is already defined. Rename this
member or use different parameter types
prog.cs(7,16): (Location of the symbol related to previous error)

7. Explain the concept of multilevel inheritance along with example?

In the Multilevel inheritance, a derived class will inherit a base class and as well as the derived
class also act as the base class to other class. For example, three classes called A, B, and C, as
shown in the below image, where class C is derived from class B and class B, is derived from
class A. In this situation, each derived class inherit all the characteristics of its base classes. So
class C inherits all the features of class A and B.
Example: Here, the derived class Rectangle is used as a base class to create the derived class
called ColorRectangle. Due to inheritance the ColorRectangle inherit all the characteristics of
Rectangle and Shape and add an extra field called rcolor, which contains the color of the
rectangle.

This example also covers the concept of constructors in a derived class. As we know that a
subclass inherits all the members (fields, methods) from its superclass but constructors are not
members, so they are not inherited by subclasses, but the constructor of the superclass can be
invoked from the subclass. As shown in the below example, base refers to a constructor in the
closest base class. The base in ColorRectangle calls the constructor in Rectangle and the base in
Rectangle class the constructor in Shape.

filter_none
edit
play_arrow

brightness_4
// C# program to illustrate the
// concept of multilevel inheritance
using System;

class Shape {

double a_width;
double a_length;

// Default constructor
public Shape()
{
Width = Length = 0.0;
}

// Constructor for Shape


public Shape(double w, double l)
{
Width = w;
Length = l;
}

// Construct an object with


// equal length and width
public Shape(double y)
{
Width = Length = y;
}

// Properties for Length and Width


public double Width
{
get {
return a_width;
}

set {
a_width = value < 0 ? -value : value;
}
}

public double Length


{
get {
return a_length;
}

set {
a_length = value < 0 ? -value : value;
}
}
public void DisplayDim()
{
Console.WriteLine("Width and Length are "
+ Width + " and " + Length);
}
}

// A derived class of Shape


// for the rectangle.
class Rectangle : Shape {

string Style;

// A default constructor.
// This invokes the default
// constructor of Shape.
public Rectangle()
{
Style = "null";
}
// Constructor
public Rectangle(string s, double w, double l)
: base(w, l)
{
Style = s;
}

// Construct an square.
public Rectangle(double y)
: base(y)
{
Style = "square";
}

// Return area of rectangle.


public double Area()
{
return Width * Length;
}

// Display a rectangle's style.


public void DisplayStyle()
{
Console.WriteLine("Rectangle is " + Style);
}
}

// Inheriting Rectangle class


class ColorRectangle : Rectangle {

string rcolor;

// Constructor
public ColorRectangle(string c, string s,
double w, double l)
: base(s, w, l)
{
rcolor = c;
}

// Display the color.


public void DisplayColor()
{
Console.WriteLine("Color is " + rcolor);
}
}
// Driver Class
class GFG {

// Main Method
static void Main()
{
ColorRectangle r1 = new ColorRectangle("pink",
"Fibonacci rectangle", 2.0, 3.236);

ColorRectangle r2 = new ColorRectangle("black",


"Square", 4.0, 4.0);

Console.WriteLine("Details of r1: ");


r1.DisplayStyle();
r1.DisplayDim();
r1.DisplayColor();

Console.WriteLine("Area is " + r1.Area());


Console.WriteLine();

Console.WriteLine("Details of r2: ");


r2.DisplayStyle();
r2.DisplayDim();
r2.DisplayColor();

Console.WriteLine("Area is " + r2.Area());


}
}
Output:
Details of r1:
Rectangle is Fibonacci rectangle
Width and Length are 2 and 3.236
Color is pink
Area is 6.472

8. Write note on Sealed classes, Garbage collector

Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by
using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore,
cannot be extended. No class can be derived from a sealed class.

The following is the syntax of a sealed class :

sealed class class_name


{
// data members
// methods
.
.
.

}
A method can also be sealed, and in that case, the method cannot be overridden. However, a
method can be sealed in the classes in which they have been inherited. If you want to declare a
method as sealed, then it has to be declared as virtual in its base class.

The following class definition defines a sealed class in C#:

In the following code, create a sealed class SealedClass and use it from Program. If you run this
code then it will work fine.

filter_none
edit
play_arrow

brightness_4
// C# code to define
// a Sealed Class
using System;

// Sealed class
sealed class SealedClass {

// Calling Function
public int Add(int a, int b)
{
return a + b;
}
}

class Program {

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

// Creating an object of Sealed Class


SealedClass slc = new SealedClass();

// Performing Addition operation


int total = slc.Add(6, 4);
Console.WriteLine("Total = " + total.ToString());
}
}
Output :

Total = 10
Now, if it is tried to inherit a class from a sealed class then an error will be produced stating that
” It cannot be derived from a Sealed class.

filter_none
edit
play_arrow

brightness_4
// C# code to show restrictions
// of a Sealed Class
using System;

class Bird {

// Creating a sealed class


sealed class Test : Bird {
}

// Inheriting the Sealed Class


class Example : Test {
}

// Driver Class
class Program {

// Main Method
static void Main()
{
}
}
Error:

Error CS0509 ‘Example’ : cannot derive from sealed type ‘Test’


Consider the following example of a sealed method in a derived class :

filter_none
edit
play_arrow

brightness_4
// C# program to
// define Sealed Class
using System;

class Printer {

// Display Function for


// Dimension printing
public virtual void show()
{
Console.WriteLine("display dimension : 6*6");
}

// Display Function
public virtual void print()
{
Console.WriteLine("printer printing....\n");
}
}

// inherting class
class LaserJet : Printer {

// Sealed Display Function


// for Dimension printing
sealed override public void show()
{
Console.WriteLine("display dimension : 12*12");
}

// Function to override
// Print() function
override public void print()
{
Console.WriteLine("Laserjet printer printing....\n");
}
}

// Officejet class cannot override show


// function as it is sealed in LaserJet class.
class Officejet : LaserJet {

// can not override show function or else


// compiler error : 'Officejet.show()' :
// cannot override inherited member
// 'LaserJet.show()' because it is sealed.
override public void print()
{
Console.WriteLine("Officejet printer printing....");
}
}

// Driver Class
class Program {

// Driver Code
static void Main(string[] args)
{
Printer p = new Printer();
p.show();
p.print();

Printer ls = new LaserJet();


ls.show();
ls.print();

Printer of = new Officejet();


of.show();
of.print();
}
}
Output :

display dimension : 6*6


Printer printing....

display dimension : 12*12


LaserJet printer printing....

display dimension : 12*12


Officejet printer printing....
Explanation: In above C# code, Printer class has display unit with the dimension of 6*6 and
LaserJet class have implemented show method by overriding it to have the dimension of 12*12.
If any class will inherit LaserJet class then it will have the same dimension of 12*12 and can’t
implement its own i.e. it cannot have 15*15, 16*16 or any other dimensions. So, LaserJet call
will seal the show method to prevent further overriding of it.

Why Sealed Classes?

Sealed class is used to stop a class to be inherited. You cannot derive or extend any class from it.
Sealed method is implemented so that no other class can overthrow it and implement its own
method.
The main purpose of the sealed class is to withdraw the inheritance attribute from the user so that
they can’t attain a class from a sealed class. Sealed classes are used best when you have a class
with static members.
e.g the “Pens” and “Brushes” classes of the System.Drawing namespace. The Pens class
represents the pens for standard colors. This class has only static members. For example,
“Pens.Red” represents a pen with red color. Similarly, the “Brushes” class represents standard
brushes. “Brushes.Red” represents a brush with red color.

Garbage Collector:
The garbage collector (GC) manages the allocation and release of memory. The garbage
collector serves as an automatic memory manager.

You do not need to know how to allocate and release memory or manage the lifetime of the
objects that use that memory.

An allocation is made any time you declare an object with a “new” keyword or a value type is
boxed. Allocations are typically very fast.

When there isn’t enough memory to allocate an object, the GC must collect and dispose of
garbage memory to make memory available for new allocations.

This process is known as garbage collection.

Garbage Collection in C# has the following advantages −

You don’t need to free memory manually while developing your application.

It also allocates objects on the managed heap efficiently.

When objects are no longer used then it will reclaim those objects by clearing 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.

9. What is Enumeration. Explain C# enum with example?


An enumeration is a set of named integer constants. An enumerated type is declared using the
enum keyword.

C# enumerations are value data type. In other words, enumeration contains its own values and
cannot inherit or cannot pass inheritance.

Declaring enum Variable


The general syntax for declaring an enumeration is −

enum <enum_name> {
enumeration list
};
Where,

The enum_name specifies the enumeration type name.

The enumeration list is a comma-separated list of identifiers.

Each of the symbols in the enumeration list stands for an integer value, one greater than the
symbol that precedes it. By default, the value of the first enumeration symbol is 0. For example −

enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };


Example
The following example demonstrates use of enum variable −

Live Demo
using System;

namespace EnumApplication {
class EnumProgram {
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

static void Main(string[] args) {


int WeekdayStart = (int)Days.Mon;
int WeekdayEnd = (int)Days.Fri;

Console.WriteLine("Monday: {0}", WeekdayStart);


Console.WriteLine("Friday: {0}", WeekdayEnd);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −

Monday: 1
Friday: 5
10. Write a program to search an element in the array?

using System;
using System.IO;
class Program
{
static void Main()
{

string[] array1 = { "cat", "dogs", "donkey", "camel" };


string v1 = Array.Find(array1,
element => element.StartsWith("cam", StringComparison.Ordinal));
string v2 = Array.Find(array1,
element => element.Length == 3);
Console.WriteLine("The Elemnt that Starts with 'Cam' is : " +v1);
Console.WriteLine("3 Letter word in the Array is : " +v2);
Console.ReadLine();
}
}
11. What is StringBuilder? Explain the use in string manipulation with example?

Like string in c#, we can use a StringBuilder to create a variables to hold any kind of text which
is a sequential collection of characters based on our requirements.

In c#, both string and StringBuilder will represent a sequence of characters and perform a same
kind of operations but only difference is strings are immutable and StringBuilder is mutable.

Generally, in c# the string object cannot be modified once it created. If any changes made to the
string object like add or modify an existing value, then it will simply discard the old instance in
memory and create a new instance to hold the new value. In case, if we are doing a repeated
modifications on the string object, then it will effect the performance of application. To know
more about strings, check this strings in c# with examples.

To solve this problem, c# introduced an alternative called StringBuilder, which is a mutable


string class. Mutability means once an instance of class is created, then the same instance will be
used to perform any operations like inserting, appending, removing or replacing the characters
instead of creating a new instance for every time.
In c#, the StringBuilder is a dynamic object which will expands a memory dynamically to
accommodate the modifications of string instead of creating a new instance in the memory.

Following is the pictorial representation of memory allocation for StringBuilder object in c#


programming language.

C# StringBuilder Memory Representation Diagram

C# StringBuilder Declaration and Initialization


As discussed, the StringBuilder class is an object of System.Text namespace so to use
StringBuilder in our application, we need to import System.Text namespace.

In c#, the StringBuilder declaration and initialization will be same like class. Following are the
different ways of declaring and initializing a stringbuilder in c# programming language.

StringBuilder sb = new StringBuilder();

//or

StringBuilder sb = new StringBuilder("Welcome to Tutlane");

If you observe above code snippet, we created an instance of StringBuilder class by defining our
variable with overloaded constructor methods.

C# StringBuilder Capacity
As discussed, the StringBuilder is a dynamic object which will expands dynamically to
accommodate the number of characters based on the string modifications. We can also specify an
initial capacity of characters, the StringBuilder can hold by passing an int value using one of the
overloaded constructors or by using StringBuilder Capacity property.
For example, we created a StringBuilder by specifying a capacity of 25 characters and appending
a string whose length is greater than the capacity of 25 characters. In this case, the new space
will be allocated automatically and the capacity of StringBuilder will be doubled.

Following is the example of specifying the initial capacity of characters the StringBuilder can
hold in c# programming language.

StringBuilder sb = new StringBuilder(25);

//or

StringBuilder sb = new StringBuilder("Welcome to Tutlane",25);

//or

sb.Capacity = 25;

In c#, whenever the defined capacity of StringBuilder is lesser than the appended string value,
then the current capacity of StringBuilder automatically will increase to match the appended
string value.

The default capacity of StringBuilder is 16 characters and its maximum capacity is more than 12
billion characters.

C# StringBuilder Methods
Following table lists the important methods of StringBuilder which we can use to modify the
contents of StringBuilder.

Method Description
StringBuilder.Append This method will append the given string value to the end of current
StringBuilder.
StringBuilder.AppendFormat It will replaces a format specifier passed in a string with formatted
text.
StringBuilder.Insert It inserts a string at the specified index of current StringBuilder.
StringBuilder.Remove It removes a specified number of characters from the current
StringBuilder.
StringBuilder.Replace It replaces a specified character at a specified index.
C# StringBuilder Append Method
The Append method is used to add or append a string objects to the end of string represented by
the StringBuilder.

Following is the example of initializing a StringBuilder with some text and appending a required
text to the end of string object.

StringBuilder sb = new StringBuilder("Suresh");

sb.Append(", Rohini");

sb.Append(", Trishika");

Console.WriteLine(sb);

// Output: Suresh, Rohini, Trishika

C# StringBuilder AppendFormat Method


The AppendFormat method is used to add or append a string objects by formatting into specified
format at the end of string represented by the StringBuilder.

Following is the example of initializing a StringBuilder with some text and appending a
formatted text to the end of string object.

int amount = 146;

StringBuilder sb = new StringBuilder("Total");

sb.AppendFormat(": {0:c}", amount);


Console.WriteLine(sb);

// Output is Total: $146.00

C# StringBuilder Insert Method


The Insert method is used to insert a string at the specified index position of current
StringBuilder object.

Following is the example of initializing a StringBuilder with some text and inserting a string at
the specified index position of StringBuilder object.

StringBuilder sb = new StringBuilder("Welcome Tutlane");

sb.Insert(8, "to ");

Console.WriteLine(sb);

// Output: Welcome to Tutlane

C# StringBuilder Remove Method


The Remove method is used to remove a specified number of characters from the current
StringBuilder object, starting from the specified index position.

Following is the example of removing a specified number of characters from the StringBuilder
object, starting from the specified index position.

StringBuilder sb = new StringBuilder("Welcome to Tutlane");

sb.Remove(8, 3);

Console.WriteLine(sb);

// Output: Welcome Tutlane

C# StringBuilder Replace Method


The Replace method is used to replace all occurrences of specified string characters in current
StringBuilder object with a specified replacement string characters.
Following is the example of replacing a specified number of characters from the StringBuilder
object, with specified replace characters.

StringBuilder sb = new StringBuilder("Welcome to Tutlane");

sb.Replace("Tutlane","C#");

Console.WriteLine(sb);

// Output: Welcome to C#

In c#, the StringBuilder is having another method called AppendLine() which is used to add a
newline to the end of string.

C# StringBuilder Example
Following is the example of using StringBuilder to insert or append or replace or to remove a
particular string text in c# programming language.

using System;

using System.Text;

namespace Tutlane

class Program

static void Main(string[] args)

StringBuilder sb = new StringBuilder("Suresh");

sb.Append(", Rohini");
sb.Append(", Trishika");

sb.AppendLine();

sb.Append("Welcome to Tutlane");

Console.WriteLine(sb);

StringBuilder sb1 = new StringBuilder("Welcome World");

sb1.Insert(8, "to Tutlane ");

Console.WriteLine("Insert String: " + sb1);

StringBuilder sb2 = new StringBuilder("Welcome to Tutlane");

sb2.Remove(8, 3);

Console.WriteLine(sb2);

StringBuilder sb3 = new StringBuilder("Welcome to Tutlane World");

sb3.Replace("Tutlane", "C#");

Console.WriteLine(sb3);

Console.ReadLine();

If you observe above code, to use StringBuilder in our application we imported a System.Text
namespace and used a different methods of StringBuilder to make required modifications based
on our requirements.
When we execute above c# program, we will get the result like as shown below.

C# StringBuilder Example Result

This is how we can use StringBuilder in our applications to make required modifications to the
string objects based on our requirements.

C# Convert StringBuilder to String


In c#, we can convert a StringBuilder object to string by calling by StringBuilder.ToString()
method.

Following is the example of converting a StringBuilder object to string using ToString() method
in c# programming language.

using System;

using System.Text;

namespace Tutlane

class Program

static void Main(string[] args)

StringBuilder sb = new StringBuilder("Suresh");

sb.Append(", Rohini");

sb.Append(", Trishika");
sb.AppendLine();

sb.Append("Welcome to Tutlane");

Console.WriteLine(sb.ToString());

Console.ReadLine();

If you observe above code, we are converting StringBuilder object (sb) to string object using
sb.ToString() method.

When we execute above c# program, we will get the result like as shown below.

C# Convert StringBuilder to String Example Result

This is how we can convert StringBuilder object to string based on our requirements.

In c#, the StringBuilder will offer a better performance than string but we should not
automatically replaces a string with StringBuilder whenever we want to manipulate a strings.
Use StringBuilder in C#
Following are the important points which we needs to remember while using a StringBuilder in
c# programming language.

We need to consider using StringBuilder only when we are unknown about the number of
changes which will make to a string at design time otherwise StringBuilder will offer a
negligible or no performance improvement over string.
When we are performing a fixed number of concatenation operations on string, then it’s better to
avoid using StringBuilder because it will offer negligible performance.
In another case when we expect our application will make a significant number of changes to a
string, then we need to use StringBuilder instead of string.

12. Write a program to copy the content of one file to another?

FileStream fin=new FileStream("text1.txt",FileMode.Open);


FileStream fout=new FileStream("text2.txt",FileMode.Create);

try
{
do{
i=fin.ReadByte();
if(i!= -1) fout.WriteByte((byte)i);

}while(i!=-1);
}catch{Console.WriteLine("error");}
Console.WriteLine("reading is over");
Console.ReadLine();

13. Explain architecture of Microsoft Framework?

The .NET Framework is a new and revolutionary platform created by Microsoft for developing
applications

 It is a platform for application developers


 It is a Framework that supports Multiple Language and Cross languageintegration.
 IT has IDE (Integrated Development Environment).
 Framework is a set of utilities or can say building blocks of your application system.
 .NET Framework provides GUI in a GUI manner.
 .NET is a platform independent but with help of Mono Compilation System (MCS). MCS
is a middle level interface.
 .NET Framework provides interoperability between languages i.e. Common Type System
(CTS) .
 .NET Framework also includes the .NET Common Language Runtime (CLR), which is
responsible for maintaining the execution of all applications developed using the .NET
library.
 The .NET Framework consists primarily of a gigantic library of code.

Definition: A programming infrastructure created by Microsoft for building, deploying, and


running applications and services that use .NET technologies, such as desktop applications and
Web services.

Cross Language integration

You can use a utility of a language in another language (It uses Class Language Integration).
.NET Framework includes no restriction on the type of applications that are possible. The .NET
Framework allows the creation of Windows applications, Web applications, Web services, and
lot more.

The .NET Framework has been designed so that it can be used from any language, including C#,
C++, Visual Basic, JScript, and even older languages such as COBOL.

Difference between Visual Studio and Visual Studio .NET


Visual Studio Visual Studio .Net
It is object based It is object oriented
Internet based application
- Web Application
- Web services
All developing facilities in internet based application
- Internet enable application
- Third party API
- Peer to peer Application
Poor error handling
Advance error handler and debugger
Exception/Error
Memory Management System Memory Management Application Domain with help of GC
Level Task (Garbage Collector)
DLL HELL VS .NET has solved DLL HELL Problem

Simple explanation of definition used in the above comparision:

Web Application

All websites are example of web application. They use a web server.

Internet Enabled Application

They are desktop application. Yahoo messenger is an example of desktop application.

Peer to Peer

Communication through computers through some system.

Web Services

It doesn't use web-based server. Internet payment systems are example of web services.

DLL Hell

"DLL Hell" refers to the set of problems caused when multiple applications attempt to share a
common component like a dynamic link library (DLL) or a Component Object Model (COM)
class.
The reason for this issue was that the version information about the different components of an
application was not recorded by the system. (Windows Registry cannot support the multiple
versions of same COM component this is called the dll hell problem.)

.Net Framework provides operating systems with a Global Assembly Cache (GAC). This Cache
is a repository for all the .Net components that are shared globally on a particular machine. When
a .Net component is installed onto the machine, the Global Assembly Cache looks at its version,
its public key, and its language information and creates a strong name for the component. The
component is then registered in the repository and indexed by its strong name, so there is no
confusion between different versions of the same component, or DLL.

Architecture of .NET Framework


Architecture of CLR

CLS (Common Language Specification)

It is a subset of CTS. All instruction is in CLS i.e. instruction of CTS is written in CLS.

Code Manager

Code manager invokes class loader for execution.

.NET supports two kind of coding

1. Managed Code
2. Unmanaged Code
14. What are the benefits of multiple language integration? Explain?
The most ambitious aspect of the CLR is that it is designed to support multiple languages and
allow unprecedented levels of integration among those languages. By enforcing a common type
system, and by having complete control over interface calls, the CLR allows languages to work
together more transparently than ever before.

Previously, one language could instantiate and use components written in another language by
using COM. Sometimes calling conventions were difficult to manage, especially when Visual
Basic was involved, but it could generally be made to work. However, subclassing a component
written in a different language required a sophisticated wrapper, and only advanced developers
did such work.

It is straightforward in the .NET Framework to use one language to subclass a class implemented
in another language. A class written in Visual Basic can inherit from a base class written in C++,
or in COBOL for that matter (at least one major vendor is at work on a COBOL implementation
for .NET). The VB program doesn't even need to know the language used for the base class, and
we're talking full implementation inheritance with no problems requiring recompilation when the
base
class changes.

How can this work? The information furnished by metadata makes it possible. There is no
Interface Definition Language (IDL) in .NET because none is needed. A class interface looks the
same, regardless of the language that generated it. The CLR uses metadata to manage all the
interfaces and calling conventions between languages.

This has major implications; mixed language programming teams become far more feasible than
before. And it becomes less necessary to force developers who are perfectly comfortable in one
language to adopt another just to fit into a development effort. Cross-language inheritance
promises to open up architectural options than never existed before.

One Microsoft person summed this up by saying that, as far as they are concerned, with .NET,
the language used becomes a "lifestyle choice". While there will always be benefits to
programming teams using a common language, .NET raises the practicality of mixed-language
projects.

A Common Type System

A key piece of functionality that enables Multiple Language Support is a Common Type System,
in which all commonly used data types, even base types such as Longs and Booleans, are
actually implemented as objects. Coercion among types can now be done at a lower level for
more consistency between languages. And, since all languages are using the same library of
types, calling one language from another doesn't require type conversion or weird calling
conventions.
This results in the need for some readjustment, particularly for Visual Basic developers. For
example, what we called an Integer in VB6 and earlier, is now known as a Short in Visual
Basic.NET. The adjustment is well worth the effort in order to bring VB in line with everything
else - and, as a by-product, other languages get the same support for strings that VB has always
had.

15. write short notes on namespace, user interface?

This a basic question which allways asked in the interview that what is the namespace ,do you
know about namespace,can you tell me some words about namespace.

NameSpace is the Logical group of types or we can say namespace is a container (e.g Class,
Structures, Interfaces, Enumerations, Delegates etc.), example System.IO logically groups
input output related features , System.Data.SqlClient is the logical group of ado.net Connectivity
with Sql server related features. In Object Oriented world, many times it is possible that
programmers will use the same class name, Qualifying NameSpace with class name can avoid
this collision.

Example :-
// Namespace Declaration
using System;

// The Namespace
namespace MyNameSpace
{
// Program start class
class MyClass
{
//Functionality

Namespaces allow you to create a system to organize your code. A good way to organize your
namespaces is via a hierarchical system. You put the more general names at the top of the
hierarchy and get more specific as you go down. This hierarchical system can be represented by
nested namespaces. Bellow shows how to create a nested namespace. By placing code in
different sub-namespaces, you can keep your code organized.

User Interface
Window Forms
Windows forms (also called Win Forms) ate used to create GUI-for Windows desktop
applications. The idea of Win Form has been borrowed from Windows Foundation Classes
(WFC) which was used for Visual J++. Win Form provide an integrated and unified way of
developing -GUI. It has a rich variety of windows controls and user interface support.
Numerous classes and functions were used by programmers to handle GUT. MFC in VC++,
direct API in C++ and VB Forms Engine in VB are just a few examples of different ways of
handling GUI.
Simply Win Form is just another group of wrapper classes that deal specifically with GUI. Win
Form classes encapsulate the Windows Graphical APIs. Now the programmers would not need
to use the Windows Graphical APIs directly; and since Win Form has been made apart of .NET.
Class Framework; all the programming languages would use the same Win Form classes. This
would rid the programmers of the need to learn different· GUI classes/tools. Win Forms in the
part of the namespace System Winforms.
With Win Forms we can make a single user interface, and use it in VC++, VB, C#. Using
Visual Studio. NET simply designs the GUI, by dragging the controls on a form (something that
all VC++ and VB programmers are well familiar with). Now you can use the same form either in
VB, VC++ or in C#. And this is all made possible because Visual Studio.NET uses the System.
Winforms namespace to draw the GUI. And any language that has the appropriate CLS
compliance can use this form directly.
Web Forms
Just as the Win Forms provide a unified way of developing GUI for desktop application, the
Web Forms provide similar tool for web applications. Web Forms has been introduced in .NET
as a part of ASP.NET. Web' Forms are a form engine, that provides a browser-based user
interface.
To appreciate Web Forms you may consider how GUI is rendered in current Web applications.
The GUI is rendered by using HTML tags. (e.g. <input type=text name=editboxl maxlength=10
size=10 >, will draw an edit box on the web page) Web Forms can also have the intelligence to
use HTML, DHTML, and WML etc. to draw the controls on the web page based on the
browser's capabilities. Web Forms can also incorporate the logic behind these controls. It’s like
hooking up the code to a GUI control. Just like in your VB application, you can associate a code
with a button on the web page; this code will be run on the server when the button is pressed.
This is in contrast to the scripts that run on the clients when a button is pressed.
This approach is different to the Java approach. In Java a programmer can simulate this
functionality through JavaScript and Servlets. But with Web forms this is done transparently.
A Java programmer may consider as if each HTML control has its dedicated "Servlets" running
in the background. Every time the control receives any event of interest (e.g. button pressed,
selection changed etc.) this specific "Servlets" is called. This results in much cleaner code and an
excellent logic separation between presentation and business logic layers.
Web Forms consist of two parts - a template, which contains HTML-based
layout information for all the GUI elements and a Component which contains all the logic to be
hooked to the controls or GUI elements. This provides a neat presentation layer and application
logic layer separation.
The GUI will be rendered on the client side, while the code that has been hooked to the GUI
elements will run on the server side (very 'much likes a button being pressed on a JSP and a
Servlets being called in response. But with Win Forms this has been made extremely easy). The
incorporation of Web Forms in ASP.NET is an attempt to take ASP to a new level where it can
seriously challenge JSP.
Another good feature of Web Forms is that it can be built to have enough intelligence to support
a vast variety of browsers. The same ASP page would render itself using DHTML, if the browser
is IE 5.5. But if the browser is Netscape the web page will be rendered using HTML tags; if the'
page is being accessed through a WAP device the same page will render itself using WML tags.
One of the obvious disadvantages of ASP over Java was that there was that an ASP code was a
maintenance nightmare. While a Java programmer can use Java Beans, Tags and also Servlets to
achieve presentation and business layer separation - no such mechanism was present to an ASP
programmer. With ASP.NET Microsoft 'has provided such presentation business, layer
separation - by introducing the concept of Web Forms:
1. ASP.NET Web Forms provide an easy and to build dynamic Web UI.
2. ASP.NET Web Forms pages can target any browser client (there are no script library or.
cookie requirements).
3. ASP.NET Web Forms pages· provide syntax compatibility with existing ASP pages.
4. ASP.NET server controls provide an easy way to encapsulate common functionality.
5. ASP.NET ships with 45 built-in server controls. Developers can also use controls built by
third parties.
6. ASP.NET templates provide an easy way to customize the look and feel of list server controls.
7. ASP.NET validation controls provide an easy way to do declarative client ·or server data
validation.
Console Application
Console applications are command line oriented applications that allow user to read characters
from the· console, write characters to the console.
Console applications are typically designed without graphical user interface and are compiled in
a stand-alone executable file.
A console application is run from the command line with input and output information being
exchanged between the command prompt and the running application. Because information can
be written to and read from .the console window, this makes the console application a great way
to learn new programming techniques without having to be concerned with the user interface.
Web Services
A web service is an extension of ActiveX. Those programmers, who have used ASP and JSP
both, know the apparent shortcomings of ASP. JSP has been enriched with the concepts of
Beans. And Tags. ASP equivalent for Beans and Tags was ActiveX Controls. and ActiveX
automation servers. Let me take a minute to explain this point a bit further. Web Services is NOT
a Microsoft proprietary standard. It is a W3Consortium standard, and has been developed by
Microsoft, IBM and many other big names of the industry.
Functions are of two types. The ASP built-in functions and the programmer defined implemented
functions. In order to use the built in functions you just need to pass the appropriate parameters
and make a simple call to these functions. The functions are implemented by the ASP itself. The
string manipulation functions, Number conversion functions are an, example of built in
functions.
The user-defined functions are the functions that are defined and implemented by the
programmer. A programmer can either write these functions in the same asp file or can write
them in another file. If the function code resides in the same asp file then the programmer can
directly call that function. In case the function resides in another file, say "func.asp"; then the
programmer needs to include that file by writing a statement like <!- #include file="func.asp" ->;
and now the programmer can use the function. The programmers can also make ActiveX
automation servers, and call various functions of these ActiveX servers, But one limitation is
very obvious - no matter which type of function you use, the function MUST physically reside on
the same machine. For example your ActiveX automation server must be implemented either as
a .dll or as an .exe and then must also be registered in Windows Registry before an asp code can
call its functions.
In a world where the Intemet has become not only a necessity but also a way of life – it is
obvious that this limitation is a strong one; Microsoft's answer to this problem is "Web Services".
The idea goes something like this:
1. The Web service provider develops a useful function(s), and publish/advertise it. The
Web Service provider uses Web Service Description Language (WSDL) standard to describe the
interface of the function(s). This is much like the Type Libraries (TLB) and Object Description
Language files (ODL) that needs to be generated with the ActiveX automation servers.
2. The programmer/client who needs the function does a lookup by using a process called
- Web Service Discovery or SOAP Discovery (also called DISCO for Web Service DISCOvery)
3. The Actual communication between the client program and the web service takes place
through a protocol called Simple Object Access Protocol (SOAP) -SOAP is an XML based light
weight protocol used for communication in a decentralized distributed environment.
16. What are web services? Explain the web services provided in C#?

A Web Service is a software program that uses XML to exchange information with other
software via common internet protocols. In a simple sense, Web Services are a way of
interacting with objects over the Internet.

A web service is

 Language Independent.
 Protocol Independent.
 Platform Independent.
 It assumes a stateless service architecture.
 Scalable (e.g. multiplying two numbers together to an entire customer-relationship
management system).
 Programmable (encapsulates a task).
 Based on XML (open, text-based standard).
 Self-describing (metadata for access and use).
 Discoverable (search and locate in registries)- ability of applications and developers to
search for and locate desired Web services through registries. This is based on UDDI.

Web Service History

 Microsoft coined the term "Web services" in June 2000, when the company introduced
Web services as a key component of its .Net initiative, a broad new vision for embracing
the Internet in the development, engineering and use of software.
 As others began to investigate Web services, it became clear that the technology could
revolutionize (be the next stage in) distributed computing.
 Web services encom a set of related standards that can enable any two computers to
communicate and exchange data via a network, such as the Internet.
 The primary standard used in Web services is the Extensible Markup Language (XML)
developed by the World Wide Web Consortium (W3C).
 Developers use XML tags to describe individual pieces of data, forming XML
documents, which are text-based and can be processed on any platform.
 XML provides the foundation for many core Web services standards (SOAP, WSDL, and
UDDI) and vocabularies (XML-based markup for a specific industry or purpose).
 Almost every type of business can benefit from Web services such as expediting software
development, integrating applications and databases, and automating transactions with
suppliers, partners, and clients.

Key Web Service Technologies

 XML- Describes only data. So, any application that understands XML-regardless of the
application's programming language or platform has the ability to format XML in a
variety of ways (well-formed or valid).
 SOAP- Provides a communication mechanism between services and applications.
 WSDL- Offers a uniform method of describing web services to other programs.
 UDDI- Enables the creation of searchable Web services registries.

When these technologies are deployed together, they allow developers to package applications as
services and publish those services on a network.

Web services advantages

 Use open, text-based standards, which enable components written in various languages
and for different platforms to communicate.
 Promote a modular approach to programming, so multiple organizations can
communicate with the same Web service.
 Comparatively easy and inexpensive to implement, because they employ an existing
infrastructure and because most applications can be repackaged as Web services.
 Significantly reduce the costs of enterprise application (EAI) integration and B2B
communications.
 Implemented incrementally, rather than all at once which lessens the cost and reduces the
organizational disruption from an abrupt switch in technologies.
 The Web Services Interoperability Organization (WS-I) consisting of over 100 vendors
promotes interoperability.

Web Services Limitations

 SOAP, WSDL, UDDI- require further development.


 Interoperability.
 Royalty fees.
 Too slow for use in high-performance situations.
 Increase traffic on networks.
 The lack of security standards for Web services.
 The standard procedure for describing the quality (i.e. levels of performance, reliability,
security etc.) of particular Web services – management of Web services.
 The standards that drive Web services are still in draft form (always will be in
refinement).
 Some vendors want to retain their intellectual property rights to certain Web services
standards.

Web Service Example

A web service can perform almost any kind of task.

 Web Portal- A web portal might obtain top news headlines from an Associated press web
service.
 Weather Reporting- You can use Weather Reporting web service to display weather
information in your personal website.
 Stock Quote- You can display latest update of Share market with Stock Quote on your
web site.
 News Headline: You can display latest news update by using News Headline Web
Service in your website.
 You can make your own web service and let others use it. For example you can make
Free SMS Sending Service with footer with your companies advertisement, so whosoever
uses this service indirectly advertises your company. You can apply your ideas in N no.
of ways to take advantage of it.

17. Explain the functions performed by CLR in DotNet framework?

CLR (Common Language Runtime) is basic component of .NET Framework. It provides an


environment to run .NET applications on targeted machine. CLR provides environment for all
.NET languages compilers for converting source code into a common language known
as IL or MSIL or CIL.

CLR provides multiple services to execute processes, like memory management service and
security services. CLR performs multiple tasks to manage the execution of .NET
applications. Following responsibilities of CLR are given below:
1. Automatic memory management
2. Code access security
3. Garbage collection
4. JIT compilation

1) Automatic memory management CLR calls various predefined functions of .NET framework
to allocate and de-allocate memory of .NET objects. So that, developers need not to write code to
explicitly allocate and de-allocate memory.
2) Code access security
CLR allows access to code to perform only those tasks for that it has permission. It also checks
user’s permissions using authentication and configuration files of .NET applications.
3) Garbage collection
GC is used to prevent memory leaks or holes. Garbage collector of CLR automatically
determines the best time to free the memory, which is allocated to an object for execution.
4) JIT compilation
JIT stands for Just In Time. It is also an important part of Common Language Runtime (CLR),
JIT compiler converts MSIL code to targeted machine code for execution.

18. Explain with example how boxing and unboxing acts as a bridge between value type and
reference type?

Boxing and unboxing enable a unified view of the type system wherein a value of any type can
ultimately be treated as an object. Converting a value type into reference type is called Boxing.
Unboxing is an explicit operation.

C# provides a "unified type system". All types including value types derive from the type object.
It is possible to call the object methods on any value, even values of "primitive" types, such as
int. The example is shown below.
using System;
class Test
{
static void Main()
{
Console.WriteLine(3.ToString());
}
}
It calls the object-defined ToString method on an integer literal. The example -
class Test
{
static void Main()
{
int i = 1;
object o = i; // boxing
int j = (int)o; // unboxing
}
}
An int value can be converted into object and back again into int.

This example shows both, boxing and unboxing. When a variable of a value type needs to be
converted into a reference type, an object box is allocated to hold the value, and the value is
copied into the box.

Unboxing is just the opposite. When an object box is cast back to its original value type, the
value is copied out of the box and into the appropriate storage location.

Boxing conversions

A boxing conversion permits any value-type to be implicitly converted to the type object or to
any interface-type implemented by the value-type. Boxing a value of a value-type consists of
allocating an object instance and copying the value-type value into that instance.

For example, for any value-type G, the boxing class would be declared as follows:
class vBox
{
Gvalue;
G_Box(G g)
{
value = g;
}
}
Boxing of a value v of type G now consists of executing the expression new G_Box(v), and
returning the resulting instance as a value of type object. Thus, the statements
int i = 12;
object box = i;
conceptually correspond to,
int i = 12;
object box = new int_Box(i);
Boxing classes like G_Box and int_Box above don't actually exist and the dynamic type of a
boxed value isn't actually a class type. Instead, a boxed value of type G has the dynamic type G,
and a dynamic type check using the is operator can simply reference type G.

For example -
int i = 12;
object box = i;
if (box is int)
{
Console.Write("Box contains an int");
}
The above code will output the string "Box contains an int" on the console.

A boxing conversion implies making a copy of the value being boxed. This is different from a
conversion of a reference-type to type object, in which the value continues to reference the same
instance and simply is regarded as the less derived type object.

For example, given the declaration -


struct Point
{
public int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
the following statements -
Point p =new Point(10, 10);
object box = p;
p.x = 20;
Console.Write(((Point)box).x);
These will output the value 10 on the console because the implicit boxing operation that occurs
in the assignment of p to box causes the value of p to be copied. Had Point instead been declared
a class, the value 20 would be output because p and box would reference the same instance.

Unboxing conversions
An unboxing conversion permits an explicit conversion from type object to any value-type or
from any interface-type to any value-type that implements the interface-type. An unboxing
operation consists of first checking that the object instance is a boxed value of the given value-
type, and then copying the value out of the instance. Unboxing conversion of an object box to a
value-type G consists of executing the expression ((G_Box)box).value.

Thus, the statements,


object box = 12;
int i = (int)box;
conceptually correspond to,
object box = new int_Box(12);
int i = ((int_Box)box).value;
For an unboxing conversion to a given value-type to succeed at run-time, the value of the source
argument must be a reference to an object that was previously created by boxing a value of that
value-type. If the source argument is null or a reference to an incompatible object, an
InvalidCastException is thrown.

19. What is an assembly? Explain its different types?

Assembly is unit of deployment like EXE or a DLL. It is completely self-describing and is is a


reusable, versionable, self-describing deployment unit for types and resources it is the primary
building block of a .NET application. Assemblies provide the infrastructure to allow the runtime
to fully understand the contents of an application and to enforce the versioning and dependency
rules defined by the application.

In .Net 3 types of Assemblies are available:


1. Private Assemblies : Private Assemblies are designed to be used by one application and

2. Shared Assemblies: Microsoft offers the shared assembly for those components that must
be distributed. It centered around two principles.
Firstly, called side-by-side execution, allows the CLR to house multiple
versions of the same component on a single machine.
Secondly, termed binding, ensures that clients obtain the version of the
component they expect.

20. What is Garbage Collection? Specify its importance? Write the ways to optimize garbage
collection?
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.
This topic describes the core concepts of garbage collection.
Fundamentals of memory
The following list summarizes important CLR memory concepts.

Each process has its own, separate virtual address space. All processes on the same computer
share the same physical memory, and share the page file if there is one.

By default, on 32-bit computers, each process has a 2-GB user-mode virtual address space.

As an application developer, you work only with virtual address space and never manipulate
physical memory directly. The garbage collector allocates and frees virtual memory for you on
the managed heap.
If you are writing native code, you use Win32 functions to work with the virtual address space.
These functions allocate and free virtual memory for you on native heaps.
Virtual memory can be in three states:
Free. The block of memory has no references to it and is available for allocation.
Reserved. The block of memory is available for your use and cannot be used for any other
allocation request. However, you cannot store data to this memory block until it is committed.
Committed. The block of memory is assigned to physical storage.
Virtual address space can get fragmented. This means that there are free blocks, also known as
holes, in the address space. When a virtual memory allocation is requested, the virtual memory
manager has to find a single free block that is large enough to satisfy that allocation request.
Even if you have 2 GB of free space, the allocation that requires 2 GB will be unsuccessful
unless all of that free space is in a single address block.

You can run out of memory if you run out of virtual address space to reserve or physical space to
commit.

While developing an application, a developer creates many objects that occupy memory. An
excess amount of unmanaged memory slows down the application performance. Traditional
programming languages do not provide garbage collection features such as C
language. Although C language ideally suits for embedded systems because of its low-level
control portability and structured programming. So, working with such kind of programming
languages end up with the much effort of freeing up memory manually. Dot net provides its
native garbage collection feature and developer no longer has to explicitly free memory. Dot net
garbage collector automatically releases the memory when a block of memory is no longer need
in the program. This technique prevents memory leaks. In this article, I will explain how to
collect garbage memory or objects in dot net c#. So let’s start.

What is a garbage collector and how does it work?


The garbage collector is one of the main features provided by CLR that helps us to clean unused
managed objects. By cleaning unused managed objects it basically reclaims the memory. When a
dot net application runs it can create several objects and at given moment of time. It is very much
possible that it will not use some of those objects or it will not need some of those objects.

You might also like