You are on page 1of 25

What is ref parameter? What is out parameter?

Ref Parameter: Used to pass a parameter as a reference so that the function called will set the
value. This could be used to return more than 1 value by a function.
e.g.
public int AddMuliply( int a , int b, ref int c)
{
c = a*b;
return ( a+b);
}
The above function, returns the addition of two numbers as well as computes the multiplication
result and passes to the calling function.
Out Parameter: Used to pass values from the aspx Code-behind to the aspx page.
The difference is that for a ref parameter, you have to assign a value before you call the function,
while for OUT parameter, you dont have to assign a value, the calling function assumes that the
called function would assign some value.

a ref parameter must first be initialized before being passed from the calling function to the called
function. but a out parameter need not be initialized, we can pass it directly when we pass a
parameter as ref to a method, the method refers to the same variable and changes made will
affect the actual variable.
even the variable passed as out parameter is same as ref parameter, but implementation in c# is
different, Arguement passed as ref parameter must be initialized before it is passed to the
method. But in case of out parameter it is not necessary. But after a call to a method as out
parameter it is necessary to initialize.
When to use out and ref parameter, out parameter is used when we want to return more than one
value from a method. Ref parameter can be used as both input and o/p parameter out parameter
can be used as only output parameter

What is boxing? What is the benefits and disadvantages?


Boxing is converting a value-type to reference type. An example is converting an integer value to
an object value.

Ex:
int intValue = 10;
object obj = (object)intValue;

This is used if you want to pass variables of object types to certain functions or methods you have
created. Commonly used in events for example (Object sender...).

Why multiple Inheritance is not possible in C#?


Multple inheritance is coneceptually wrong. It shouldn't be allowed in any language. Inheritance is
the strongest relationship that can be expressed in OO languages.
It's used to express IS-A relationship. Aggregation is used to express IS CONSTRUCTED IN
TERMS OF. If you're using multiple inheritance in C++ then you're design is wrong and you
probably want to use aggregation. On the other hand it's plausible to want to use multiple
interfaces. For instance you might have a class wheel and a class engine. You could say that
your class car inherits from wheel and from engine but that's wrong. In fact car aggregates wheel
and engine because it is built in terms of those classes. If wheel is an interface and engine is an
interface then car must inherit both of these interfaces since it must implement the functionaity of
wheel and engine .On this basis we can see that multiple inheritance for classes should not be
allowed because it promotes mis-use of the strong IS-A relationship. C# enforces the correct
concepts whilst C++ allows mis-use. multiple interface inheritance is permissible and C# allows
this. It's all to do with properly understanding OO concepts.
Absolute Multiple Inheritance is not possible in c# but partially it supports multiple inheritance
by the use of Interfaces. As interfaces force a class to implement same type of behaviour (as
defined in interface) which classes implements that interface.

Which of the following is not a C# reserved keyword ? Is, As, In, Of


Answer: Of
What are Namespaces? A) Naming convention used in .Net
B) Group of classes categorized to avoid name clash C) None of the above

C. None of the above A Namespace in .Net is like containers of objects. They may contain
unions, classes, structures, interfaces, enumerators and delegates. Main goal of using
namespace in .Net is for creating a hierarchical organization of program. In this case a developer
does not need to worry about the naming conflicts of classes, functions, variables etc., inside a
project.

What are Indexers? What is the use of it, and when to use it
An indexer is a member that enables an object to be indexed in the same way as an array. There
are times when it is desirable to access a collection within a class as though the class itself were
an array. For example, suppose you create a list box control named myListBox that contains alist
of strings stored in a one-dimensional array, a private member variable named myStrings. Alist
box control contains member properties and methods in addition to its array of strings.However, it
would be convenient to be able to access the list box array with an index, just as if thelist box
were an array. This can be achieved using the Indexer

What is difference between dispose() & finalize()


if you want to delete resources(objects) those are not using ,you should not worry about that,
garbage collecter implicitly call finalize() method and remove all such object but if you want to
delete object forcefully(The larger object ,you want to delete after completeing task),than you can
explicitly call dispose() method.

Design Pattern : If your classes use unmanaged resources, you need to implement both Dispose
& Finalize. Dispose() is called by user code, that is, the code that is using your class.
Finalize/Destructor cannot be called by User code, it's called by Garbage Collector

Finalize : Is a destructor, called by Garbage Collector when the object goes out of scope.
Implement it when you have unmanaged resources in your code, and want to make sure that
these resources are freed when the Garbage collection happens.

Dispose : Same purpose as finalize, to free unmanaged resources. However, implement this
when you are writing a custom class, that will be used by other users. Overriding Dispose()
provides a way for the user code to free the unmanaged objects in your custom class.

As an aside, here's how the GC works:


The garbage collector keeps track of objects that have Finalize methods, using an internal
structure called the finalization queue. Each time your application creates an object that has a
Finalize method, the garbage collector places an entry in the finalization queue that points to that
object. The finalization queue contains entries for all the objects in the managed heap that need
to have their finalization code called before the garbage collector can reclaim their memory.

Implementing Finalize methods or destructors can have a negative impact on performance and
you should avoid using them unnecessarily. Reclaiming the memory used by objects with Finalize
methods requires at least two garbage collections. When the garbage collector performs a
collection, it reclaims the memory for inaccessible objects without finalizers. At this time, it cannot
collect the inaccessible objects that do have finalizers. Instead, it removes the entries for these
objects from the finalization queue and places them in a list of objects marked as ready for
finalization. Entries in this list point to the objects in the managed heap that are ready to have
their finalization code called. The garbage collector calls the Finalize methods for the objects in
this list and then removes the entries from the list. A future garbage collection will determine that
the finalized objects are truly garbage because they are no longer pointed to by entries in the list
of objects marked as ready for finalization. In this future garbage collection, the objects' memory
is actually reclaimed.

Dispose() is called by the user of an object to indicate that he is finished with it, enabling that
object to release any unmanaged resources it holds. Finalize() is called by the run-time to allow
an object which has not had Dispose() called on it to do the same. However

Dispose() operates determinalistically, whereas there is no guarantee that Finalize() will be called
immediately when an object goes out of scope - or indeed at all, if the program ends before that
object is GCed - and as such Dispose() is generally preferred.

In which scenerio we use interfaces, abstract and concrete class? Which one is better and
appropriate? Differentiate these three terms in depth.

The decision tree for this is pretty detailed. :) In most cases, using an abstract class is the "right"
thing to do if you're trying to create a common class from which others will derive and which isn't
fully specified. Interfaces are nice if you don't want to force classes to have a single root class in
their hierarchy, as a single class can implement multiple interfaces. Concrete classes should be
used if it's fully specified--i.e. subclasses don't have any hooks into which they must provide
functionality.
Interface - used to define a skeleton. Classes who want to confirm to that skeleton
implementsts the interface
Abstract class - Use abstract class when you want to provide some functionality to the user and
at the same time would like to enforce some skeleton (structure) for the users of your class
Concrete class - Use a concrete class to represent an object (data & methods) which can be
extended or reused.
Use following guidelines for each of the abstractions:
Interface:
-- If your child classes should all implement a certain group of methods/functionalities, but each of
the child classes is free to provide its own implementation, then use interfaces.
For e.g., if you are implementing a class hierarchy for vehicles, implement an interface called
"Vehicle", which has properties like Colour, MaxSpeed etc., and methods like Drive(). All child
classes like "Car", "Scooter", "AirPlane", "SolarCar" etc. should derive from this base interface,
but provide a seperate implementation of the methods and properties exposed by Vehicle.
-- If you want your child classes to implement multiple, unrelated functionalities, in short multiple
inheritance, use interfaces.
For e.g., if you are implementing a class called "SpaceShip", that has to have functionalities from
a "Vehicle", as well as that from a "UFO", then make both "Vehicle" and "UFO" as interfaces, and
then create a class "SpaceShip" that implements both "Vehicle" and "UFO".

Abstract Classes
-- When you have a requirement where your base class should provide default implementation of
certain methods, whereas other methods should be open to being overridden by child classes,
use abstract classes.
For e.g., again take the example of the "Vehicle" class above. If we want all classes deriving from
"Vehicle" to implement the "Drive()" method in a fixed way, whereas the other methods can be
overridden by child classes. In such a scenario, we implement the "Vehicle" class as an abstract
class with an implementation of "Drive", while leave the other methods / properties as abstract so
they could be overridden by child classes.
-- The purpose of an abstract class is to provide a common definition of a base class that multiple
derived classes can share. For example, a class library may define an abstract class that is used
as a parameter to many of its functions, and require programmers using that library to provide
their own implementation of the class by creating a derived class.

What is the difference between Abstract and Interface? Answer


In an interface class, all methods are abstract - there is no implementation.
In an abstract class some methods can be concrete - there can be implementation.
In an interface class, no accessibility modifiers are allowed - are public by default.
In an abstract class accessibility modifiers are allowed.

Abstract Class:
1. Abstract Class Can contain Abstract Methods and Non-Abstract Methods.
2. When a Non-Abstract Class is Inherited from an Abstract Class, the Non-Abstract Class should
provide all the implementations for the inherited Abstract Method.

Interface:
1. Interface is nothing but Pure Abstract Class ie Interface can contain only the function
declaration.
2. All the members of the interface are Public by Default and you cannot provide any access
modifiers.
3. When a class is inherited from the interface, the inherited class should provide actual
implementations for the inherited members.

What is the main difference between pointer and delegate with examples?
Delegates in c# are very similar to function pointers in c++ the only difference is that delegates
are type safe due to these are CLR targated under .net framework, while function pointers in c++
are not type safe.
A Delegate in c# allows to pass a method of class to object of other class.
Rules in Deligation:-
1. In order to create a Delegate a Signature(parameter) must match Signature of object.
2. Define all the methods which has the same Signature as Deligate define.
3. Create the deligate object & pass the method as a parameter to Deligate.
4. Now call the encapsulated method using deligated object.

The best example of Deligation model is ADO.NET Architecture & Event Handling in windows
environment.

Simply say Delegate is a strongly typed function pointer and pointer holds reference to a variable
or pointer is a variable which holds the address of another variable.

Delegate to function--- is same as---- pointer to object. Delegates are function pointers. They are
used when the function which needs to be called is not know at compile time. Pointers, on the
other hand, are used to point to variables or object references in unsafe code.

What is managed code?Skill/Topic: Intermediate


A) Code managed ouside the IL
B) Code which can't be managed by the IL
C) Code written in VB.NET
D) Code to be compiled by IL

D) is the correct choice. Managed code is the code written in one of 20 high level programming
languages available for use with .Net framework which is compiled into IL during the first level of
compilation.
Ans : (A) The managed code are the code which are managed by the CLR not by the executalble
code itself.(Ref.- MCSD Training Kit Developing Web Applicaion of PHI)

A is correct ans,

Ex: vbc compiler is compile to vb.net application in to MSIL(IL) code

csc compiler is compile to c#.net application code in to MSIL code

DotNet support multiple languages , each compiler will convert MSIL(IL) Code only. after CLR
execute the code in memory before taking code in CLR, JIt will compile machine understandble
code.

How to use HASH TABLE, ARRAYLIST in c# explain with example?

The ArrayList object is a collection of items containing a single data value.

Items are added to the ArrayList with the Add() method.


The following code creates a new ArrayList object named mycountries and four items are added:
<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New ArrayList
mycountries.Add("Norway")
mycountries.Add("Sweden")
mycountries.Add("France")
mycountries.Add("Italy")
end if
end sub
</script>
U can sort it alphabetically
mycountries.Sort()
By default, an ArrayList object contains 16 entries. An ArrayList can be sized to its final size with
the TrimToSize() method:
mycountries.TrimToSize()
For reversing
mycountries.Reverse()
With DB
rb.DataSource=mycountries
rb.DataBind()

The Hashtable object contains items in key/value pairs. The keys are used as indexes, and very
quick searches can be made for values by searching through their keys.

Items are added to the Hashtable with the Add() method.

The following code creates a Hashtable named mycountries and four elements are added:

<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New Hashtable
mycountries.Add("N","Norway")
mycountries.Add("S","Sweden")
mycountries.Add("F","France")
mycountries.Add("I","Italy")
end if
end sub
</script>

With DB

<html>
<body><form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" /></form></body>
</html>

----
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New Hashtable
mycountries.Add("N","Norway")
mycountries.Add("S","Sweden")
mycountries.Add("F","France")
mycountries.Add("I","Italy")
rb.DataSource=mycountries rb.DataValueField="Key" rb.DataTextField="Value" rb.DataBind()
end if
end sub
</script><html>
<body><form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" /></form></body>
</html>

What is the top .NET class that everything is derived from?


System.Objects

What is an abstract class?


The abstract modifier can be used with classes, methods, properties, indexers, and events.
Use the abstract modifier in a class declaration to indicate that a class is intended only to be a
base class of other classes.

Abstract classes have the following features:


An abstract class cannot be instantiated.
An abstract class may contain abstract methods and accessors.
It is not possible to modify an abstract class with the sealed modifier, which means that the class
cannot be inherited.
A non-abstract class derived from an abstract class must include actual implementations of all
inherited abstract methods and accessors.
Use the abstract modifier in a method or property declaration to indicate that the method or
property does not contain implementation.

Abstract methods have the following features:


An abstract method is implicitly a virtual method.
Abstract method declarations are only permitted in abstract classes.
Because an abstract method declaration provides no actual implementation, there is no method
body; the method declaration simply ends with a semicolon and there are no braces ({ }) following
the signature. For example:
public abstract void MyMethod();
abstract class is a prototype of a class. it is used to provide partial
class implementation. abstract class contain abstract method which can be implemented by
derived class.
some rules for abstract class are following-:
1) an object of an abstract class can never be created.
2)you can not declare an abstract method outside the abstract class.
3)can not be declared sealed.

WHAT IS THE ADVANTAGE OF SERIALIZATION?


Serialization is the process of maintaing object in the form stream. it is useful in case of remoting.
Serialization is the process of converting object into byte stream which is useful to transport
object(i.e remoting),persisting object(i.e files,database)
SERIALIZATION IS PROCESS OF LOADING THE OBJECT STATE IN THE FORM OF BYTE
STREAMS IN DATABASE/FILE SYATEM.

Can we inherit the java class in C# class,how?


Java Programming language is not supported with .Net Framework hence you cannot inherit
javaclass in C# class.Also Java has JavaByte code after compiling similar to MSIL which is
similar but cannot inherit due to framework support.

Are C# destructors the same as C++ destructors?


No. They look the same but they are very different. The C# destructor syntax (with the familiar ~
character) is just syntactic sugar for an override of the System.Object Finalize method. This
Finalize method is called by the garbage collector when it determines that an object is no longer
referenced, before it frees the memory associated with the object. So far this sounds like a C++
destructor. The difference is that the garbage collector makes no guarantees about when this
procedure happens. Indeed, the algorithm employed by the CLR garbage collector means that it
may be a long time after the application has finished with the object. This lack of certainty is often
termed ‘non-deterministic finalization’, and it means that C# destructors are not suitable for
releasing scarce resources such as database connections, file handles etc.

To achieve deterministic destruction, a class must offer a method to be used for the purpose.
The standard approach is for the class to implement the IDisposable interface. The user of the
object must call the Dispose() method when it has finished with the object. C# offers the ‘using’
construct to make this easier.

What is wrapper class? is it available in c#?


Wrapper Classes are the classes that wrap up the primitive values in to a class that offer utility
method to access it . For eg you can store list of int values in a vector class and access the
class. Also the methods are static and hence you can use them without creating an instance . The
values are immutable .
wrapper class are those class in which we can not define and call all predefined function .it is
possible in java not C#.

Which tool is used to browse the classes, structs, interfaces etc. in the BCL?
wincv as in Windows Class View

How is the using() pattern useful? What is IDisposable? How does it support deterministic
finalization?
The using() pattern is useful because it ensures that Dispose() will always be called when a
disposable object (defined as one that implements IDisposable, and thus the Dispose() method)
goes out of scope, even if it does so by an exception being thrown, and thus that resources are
always released.

What happens when a C# project has more than 1 Main methods


f the project is compiled using /main switch with the compiler then the project compiles
successfully.

For example:
class A
{
public static void Main(string[] args)
{
Console.WriteLine("Main in class A");
}
}

class B
{
public static void Main(string[] args)
{
Console.WriteLine("Main in class B");
}
}

Now compile with the /main switch with the C# compiler like
csc MultipleMain.cs /main:A

This will compile without error and while executing it will show Main in class A

Attempting to compile an application consisting of multiple classes with defined Main methods
and not specifying the /main switch will result in a compiler error.
How do you refer parent classes in C#? A) Super B) This C) Base
This keyword is used for reffering current object and Base keyword is used for referring parrent
class. so ans. is C.
Super: Super is used to Refer the Base Class in JAVA
This: This is used to Refer the Current or Child Class in C#
Base: Base is used to Refer The Parent or Base Class

What is object pooling


Defination: A performance optimization based on using collections of pre-allocated resources,
such as objects or database connections
With the advent of the .NET platform, writing code that pools objects and threads has become a
simple task. By using the Threading and Collections namespaces, you can create robust object
pooling applications. This could also be done by implementing COM+ interop interfaces into your
code.

Which method is actually called ultimately when Console.WriteLine( ) is invoked?


A) Append( )
B) AppendFormat( )
C) Tostring( )
Ans: B, AppendFormat() method is called.

What is an Assembly?
An assembly is a file that is automatically generated by the compiler upon successful compilation
of every .NET application. It can be either a Dynamic Link Library or an executable file. It is
generated only once for an application and upon each subsequent compilation the assembly gets
updated. The entire process will run in the background of your application; there is no need for
you to learn deeply about assemblies. However, a basic knowledge about this topic will help you
to understand the architecture behind a .NET application.

An assembly is used by the .NET CLR (Common Language Runtime) as the smallest unit for:
deployment; version control; security; type grouping and code reuse. Assemblies consists of a
manifest and one or more modules and/or files like HTML, XML, images, video clips,...

An assembly can be thought of as a logical DLL and must contain a single manifest and may
optionally contain type meta data, MSIL (Microsoft Intermediate Language) and resources.

Assemblies come in 2 flavors: application private and shared. Application private assemblies are
used by one application only. This is the default style of assembly. Such assemblies must reside
in the application folder.

Shared assemblies are meant to be used by more than one application. They must have a

globally unique name and must be defined in the GAC (Global Assembly Cache). To learn more
about viewing the GAC

Basically there are two kind of assemblies when it comes to deployment.


Private Assemblies
Shared Assemblies

Private assemblies are the ones which are in your application folder itself. They can be easily
and uniquely identified by their name.
These type of assemblies can be deployed simply by copying them to the bin folder of your
application.

Shared Assemblies are those which can be shared by multiple applications on the machine.
For this we have to place the Shared assembly in the GAC.

Now since we can install any application or assembly created by any company, that is we install
assemblies from oracle, microsoft and similarly from many other companies.

There is always a possiblity that they may use the same assembly name as your assembly name.
If such type of assemblies are placed in the GAC then we cannot uniquely identify a particular
assembly.
But if we give a strong name to the assmebly then it is like a unique identifier for the assembly.
It is Globally unique.

Strong name consists of


1. Name of the assembly
2. Public key token
3. optionally any resources
4. Version Number

So basically to uniquely identify a particular assembly from the GAC we have to give it a strong
name. Its that simple.
The Shared assembly can be deployed in to GAC by using the GACUTIL tool with the -i switch
gacutil -i assemblyname
or simply copying it to the assembly folder in the windows directory (XP) or WINNT
directory(others)
Also there are Satellite Assemblies which contian only resources like strings, images etc.
Also there are dynamic assemblies which are generated on the fly dynamically.

Is it possible to have a static indexer in C#? No. Static indexers are not allowed in C#.

base keyword
The keyword base is used to access members of the base class from inside a derived class.

Key Points:
Calling a method from the base class is possible even if it has been overriden by another method
by using the keyword base. Also, when you are creating a instance of a derived class you can
call the base classes contructor if so desired with this keyword, base.

There rules governing base class access are (or permissible in):

• in a constructor
• in an instance method
• instance property accessor

Attemps at using the keyword base in a static method will result in a error.

Example:

This brief example displays the concept of calling the base classes method even though it has
been overridden in the derived class!

<%@ Page language="c#"


%>

<script language="C#" runat="server">


public class CSharp
{
public virtual string GetMessage()
{
return "&ltbr>All your base are belong to us!";
}

// Class derived from CSharp class (above)


public class Friends: CSharp
{

// overrides CSharp classes method


public override string GetMessage()
{
return base.GetMessage();

}
}

public void Page_Load(object sender, EventArgs e)


{
Friends CSF = new Friends();
// Friend's method GetMessage calls base classes method
Response.Write(CSF.GetMessage());

}
</script>

You can call a base classes contructor from within a derived classes contructor as follows (below
is the derived classes constructor):
public DerivedClassesConstructor() : base()
{}

What is a Constructor?
A constructor is a member function that has the same name as the class name and is invoked
automatically when the class is instantiated. A constructor is used to provide initialization code
that gets executed every time the class is instantiated.
Points to be noted on constructors:
– Constructors cannot be "virtual". They cannot be inherited.
– Constructors are called in the order of inheritance.
– If we don't write any constructor for a class, C# provides an implicit default
constructor, i.e., a constructor with no argument.
– Constructors cannot return any value.
– Constructors can be overloaded.
The syntax for a constructor is as follows:
[modifier] name (parameters)
{ // constructor body
}

As per the C# specification, a constructor can have the following modifiers. public, protected,
internal, private, extern

Constructors in C# can be of two types:Static or class constructors & Non–static or


instance constructors

Static Constructors
A static constructor or class constructor gets called when the class is instantiated or a static
member of the class is used for the first time.
The following points hold good for static constructors:
A Static constructor cannot be overloaded.
It should be without parameters and can only access static members.
It cannot have any access modifiers.
The static constructor for a class executes only once in an application domain.
Static constructors cannot be chained with other static or non-static constructors.

In the program that follows, the static constructor is invoked once the static variable of the class is
referenced.

using System;
class Test
{
private static int i;
static Test()
{
Console.WriteLine ("Static Constructor.");
}
public static int Assign
{
set
{
i = value;
}
get
{
return i;
}
}
}
class Sample
{
public static void Main()
{
Test.Assign = 2;
}
}

Listing 2: Static Constructor Executes Before an Instance Constructor


using System;
class TestClass
{
static TestClass ()
{
System.Console.Write("Static ");
}
public TestClass ()
{
System.Console.Write("Instance ");
}
}
class Test
{
static void Main()
{
new TestClass ();
Console.ReadLine ();
}
}

The output of the above program is 'Static Instance'. A static constructor can only access static
members of a class. The reason is that at the time when a static constructor is loaded in the
memory, the instance members of a class are not available. In the following program, the
assignment to the non–static integer variable p inside the static constructor is an error.

Listing 3: Static Constructor Can Access Only Static Members


class Test
{
int p;
static Test()
{
p = 9;
}
public static void Main(string []args)
{
Test testObject = new Test();
/*Error: An object reference is required for the
non-static field, method,
or property 'Test.p'*/
}
}
Non-Static or Instance Constructors
Non-static constructors are also called instance constructors, type constructors, or type
initializers, and are used to create and initialize instances of the class they belong to. We can
have multiple non-static constructors but only one static constructor for a class. A non-static
constructor with no parameters is called the default constructor. If we do not write any constructor
for a class, the compiler automatically supplies one. This is the implicit default constructor. This
property of C# to supply an implicit default constructor is revoked once we write any constructor
for a class.

Non-static constructors can be public, private, protected, external, or internal. A public constructor
is one that is called when the class is instantiated. A private constructor is one that prevents the
creation of the object of the class. It is commonly used in classes that contain only static
members. A class containing an internal constructor cannot be instantiated outside of the
assembly. An internal constructor can be used to limit concrete implementations of the abstract
class to the assembly defining the class. A protected constructor allows the base class to do its
own initialization when subtypes are created. When constructor declaration includes an extern
modifier, the constructor is said to be an external constructor. An external constructor declaration
provides no actual implementation and hence does not contain any definition. It is to be noted
that a public constructor can access a private constructor of the same class through constructor
chaining.

Listing 4: Public Constructor Can Access Private Constructor of the Same Class
using System;
class Test
{
public Test(): this(10)
{
Console.WriteLine("Default Constructor");
}
private Test(int intValue)
{
Console.WriteLine("Parameterized Constructor");
}
public static void Main(string []args)
{
Test testObject = new Test();
Console.ReadLine ();
}
}
The output is as follows:
Parameterized Constructor
Default Constructor
A protected constructor can only be invoked from the subclasses of the class in which it is
defined. This is illustrated in the example that follows.

Listing 5
using system;
class B
{
protected B (string s) {}
}
class D : B
{
public D () : base ("Called from D class") {}
}
class E
{
public static void Main(string []args)
{
B x = new B ("Called from E class");
/*Error. The constructor test.B.B(string s) is inaccessible due to its
protection level*/
}
}
Constructor Overloading
A constructor can take zero or more arguments as parameters. A constructor with zero arguments
is known as the default constructor. We can have multiple constructors in a class with different
sets of signatures. Such constructors are known as “overloaded constructors”. The overloaded
constructors of a class must differ in their number of arguments, type of arguments, and/or order
of arguments. This gives the user the ability to initialize the object in multiple ways.

The class in the program shown below contains three constructors. The first is the default
constructor, followed by the two argument constructors. Note that the constructors differ in their
signature.

Listing 6: Overloaded Constructors


using system;
public class Test
{
public Test()
{
//Default constructor
}
public Test(int sampleValue)
{
// This is the constructor with one parameter.
}
public Test(int firstValue, int secondValue)
{
// This is the constructor with two parameters.
}
}

Constructor Chaining
Constructor chaining refers to the ability of a class to call one constructor from another
constructor. In order to call one constructor from another, we use base (parameters) or : this
(parameters) just before the actual code for the constructor, depending on whether we want to
call a constructor in the base class or in the current class.

Listing 7: Constructor Chaining

using system;
public class Test
{
public Test(): this(10)
{
// This is the default constructor
}
public Test(int firstValue)
{
// This is the constructor with one parameter.
}
}

Constructors and Inheritance


A constructor of a base class is not inherited to its derived class. However, a derived class
constructor can call a base class constructor, provided both are non-static.
Listing 8: Invoking a Base Constructor from the Derived Class

using System;

class Base
{
public Base()
{
Console.WriteLine("Base Constructor Version 1");
}

public Base(int x)
{
Console.WriteLine("Base Constructor Version 2");
}
}

class Derived : Base


{
public Derived():base(10)
{
Console.WriteLine("Derived Constructor");
}
}

class MyClient
{
public static void Main()
{
Derived dObject = new Derived();
//Displays 'Base Constructor Version 2' followed by 'Derived Constructor'.
}
}
Constructors are executed in the order of inheritance as shown in the example below.

Listing 9: Order of Execution of Constructors in Inheritance

using System;
class Base
{
public Base()
{
Console.WriteLine("Base constructor");
}
}
class Derived : Base
{
public Derived()
{
Console.WriteLine("Derived constructor");
}
}
class Test
{
public static void Main()
{
Derived dObject = new Derived();
//Displays 'Base constructor' followed by 'Derived constructor'.
}
}

It is not possible to inherit a class that has only a private constructor.

Listing 10: Private Constructors Prevent Inheritance

using system;
class Base
{
Base( )
{
}
}
class Derived : Base // Syntax Error.
{
public static void Main()
{
Derived dObject = new Derived ();
}
}

Conclusion

The best practice is to always explicitly specify the constructor, even if it is a public default
constructor. Proper design of constructors goes a long way in solving the challenges faced in
class designs.
C# Delegates Explained
This may be the first time you've read about this new .NET type. A delegate is an object that
refers to a static method or an instance method. In this article I discuss what delegates are, how
you can create and use them, and how the C# compiler saves us time by generating the
delegate's class. We will also look at the MSIL code, talk about multicast delegates and provide
callback methods through the use of delegates.

A delegate is an object that is created to refer to a static method or an instance method, and then
used to call this method. To start off, you create a new delegate type in a different way than you
create any other class. You use the delegate keyword as in the following statement.

public delegate int DelegateToMethod(int x, int y);

It seems unusual I know, but I will explain how it's done. Let's take a look at the very first example
that explains how to use a delegate.

The First Delegate Example

using System;
namespace Delegates
{
public delegate int DelegateToMethod(int x, int y);

public class Math


{
public static int Add(int first, int second)
{
return first + second;
}

public static int Multiply(int first, int second)


{
return first * second;
}

public static int Divide(int first, int second)


{
return first / second;
}
}

public class DelegateApp


{
public static void Main()
{
DelegateToMethod aDelegate = new DelegateToMethod(Math.Add);
DelegateToMethod mDelegate = new DelegateToMethod(Math.Multiply);
DelegateToMethod dDelegate = new DelegateToMethod(Math.Divide);
Console.WriteLine("Calling the method Math.Add() through the aDelegate object");
Console.WriteLine(aDelegate(5,5));
Console.WriteLine("Calling the method Math.Multiply() through the mDelegate object");
Console.WriteLine(mDelegate(5,5));
Console.WriteLine("Calling the method Math.Divide() through the dDelegate object");
Console.WriteLine(dDelegate(5,5));
Console.ReadLine();
}

}
}

Multicast Delegates
As you saw in the MSIL code, the delegate type that we created automatically inherits the
System.MulticastDelegate, which provides a functionality that creates a chain of delegates
through a linked list. It's better to explain with an example, so let's modify our example to use a
multicast delegate.

using System;
namespace Delegates
{
public class Math
{
// note that the delegate now is a nested type of the Math class
public delegate void DelegateToMethod(int x, int y);

public void Add(int first, int second)


{
Console.WriteLine("The method Add() returns {0}", first + second);
}

public void Multiply(int first, int second)


{
Console.WriteLine("The method Multiply() returns {0}", first * second);
}

public void Divide(int first, int second)


{
Console.WriteLine("The method Divide() returns {0}", first / second);
}
}

public class DelegateApp


{
public static void Main()
{
Math math = new Math();
Math.DelegateToMethod multiDelegate = null;
multiDelegate = new Math.DelegateToMethod(math.Add);
multiDelegate += new Math.DelegateToMethod(math.Multiply);
multiDelegate += new Math.DelegateToMethod(math.Divide);
multiDelegate(10,10);
Console.ReadLine();
}
}
}
A multicast delegate is an object that maintains a linked list of delegates. Invoking the delegate
invokes each delegate (which in turn calls its encapsulated method) in the same order that it has
been added to the linked list. In our example we have created an object (a delegate) called
multiDelegate of type Math.DelegateToMethod and assigned a null value to this object.

Operator Overloading In C#
All unary and binary operators have pre-defined implementations, that are automatically available
in any expressions. In addition to this pre-defined implementations, user defined implementations
can also be introduced in C#. The mechanism of giving a special meaning to a standard C#
operator with respect to a user defined data type such as classes or structures is known as
operator overloading. Remember that it is not possible to overload all operators in C#. The
following table shows the operators and their overloadability in C#.

Operators Overloadability

+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.

+, -, !, ~, ++, --, true, false All C# unary operators can be overloaded.

==, !=, <, >, <= , >= All relational operators can be overloaded,
but only as pairs.

&&, || They can't be overloaded

() (Conversion operator) They can't be overloaded

+=, -=, *=, /=, %= These compound assignment operators can be


overloaded. But in C#, these operators are
automatically overloaded when the respective
binary operator is overloaded.

=, . , ?:, ->, new, is, as, sizeof These operators can't be overloaded
In C#, a special function called operator function is used for overloading purpose. These special
function or method must be public and static. They can take only value arguments. The ref and
out parameters are not allowed as arguments to operator functions. The general form of an
operator function is as follows.

public static return_type operator op (argument list)


Where the op is the operator to be overloaded and operator is the required keyword. For
overloading the unary operators, there is only one argument and for overloading a binary operator
there are two arguments. Remember that at least one of the arguments must be a user-defined
type such as class or struct type.

Overloading Unary Operators The general form of operator function for unary operators is as
follows. public static return_type operator op (Type t) { // Statements } Where Type must be a
class or struct. The return type can be any type except void for unary operators like +, ~, ! and dot
(.). but the return type must be the type of 'Type' for ++ and o remember that the true and false
operators can be overloaded only as pairs. The compilation error occurs if a class declares one of
these operators without declaring the other.

The following program overloads the unary - operator inside the class Complex

// Unary operator overloading


using System;
class Complex
{
private int x;
private int y;
public Complex()
{
}
public Complex(int i, int j)
{
x = i;
y = j;
}

public void ShowXY()


{
Console.WriteLine(\"{0} {1}\",x,y);
}

public static Complex operator -(Complex c)


{
Complex temp = new Complex();
temp.x = -c.x;
temp.y = -c.y;
return temp;
}
}

class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex();
c2.ShowXY(); // displays 0 & 0
c2 = -c1;
c2.ShowXY(); // diapls -10 & -20
}
}

Overloading Binary Operators


An overloaded binary operator must take two arguments, at least one of them must be of the type
class or struct, in which the operation is defined. But overloaded binary operators can return any
value except the type void. The general form of a overloaded binary operator is as follows.

public static return_type operator op (Type1 t1, Type2 t2)


{
//Statements
}

A concrete example is given below


// binary operator overloading
using System;
class Complex
{
private int x;
private int y;
public Complex()
{
}
public Complex(int i, int j)
{
x = i;
y = j;
}

public void ShowXY()


{
Console.WriteLine(\"{0} {1}\",x,y);
}

public static Complex operator +(Complex c1,Complex c2)


{
Complex temp = new Complex();
temp.x = c1.x+c2.x;
temp.y = c1.y+c2.y;
return temp;
}
}

class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex(20,30);
c2.ShowXY(); // displays 20 & 30
Complex c3 = new Complex();
c3 = c1 + c2;
c3.ShowXY(); // dislplays 30 & 50
}
}

The binary operators such as = =, ! =, <, >, < =, > = can be overloaded only as pairs. Remember
that when a binary arithmetic operator is overloaded, corresponding assignment operators also
get overloaded automatically. For example if we overload + operator, it implicitly overloads the + =
operator also.

Summary
1.The user defined operator declarations can't modify the syntax, precedence or associativity of
an operator. For example, a + operator is always a binary operator having a predefined
precedence and an associativity of left to right.
2.User defined operator implementations are given preference over predefined implementations.
3.Operator overload methods can't return void.
4.The operator overload methods can be overloaded just like any other methods in C#. The
overloaded methods should differ in their type of arguments and/or number of arguments and/or
order of arguments. Remember that in this case also the return type is not considered as part of
the method signature.

How do you validate the controls in an ASP .NET page? Answer


By setting the control to validate property in validator to that controler

What was the difference between machine.config and web.config files Answer
machine.config
is configuration file for all the application in the IIS.
for machine level configuration.
file apply settings to all asp.net applications.
web.config
is a configuration file for a application or folder
for a application/folder level configuration
apply settings to each web application

What is collections and what is generics Answer


Collections includes of arraylist and hashtables which are similar to arrays but arrays we cant
perform delete and add operations whereas in collections it is possible some addmethods are
available
Collection in case of memory useful .its size is not fixed, means the if we want to store data more
than its default size its automatically double its default size. but in case of normal array we can do
through redim also the memory allocated is new [impact on the performance].

How to Deploy a project? Answer


By using web server or any file transer protocal(FTP) upload project or use to make virtual
directory

What does the "EnableViewState" property do? Why would I want it on or off? Answer
It allows the page to save the users input on a form across postbacks. It saves the server-side
values for a given control into ViewState, which is stored as a hidden value on the page before
sending the page to the clients browser. When the page is posted back to the server the server
control is recreated with the state stored in viewstate.

Enableviewstate propery is on for page or any control then it holding or catching or storing data
in memory as well as client side hedden value. when u post back data remains in control or page.
if Enableviewstate property false then data remove when post back.

What are the different types of Session state management options available with
ASP.NET?
ASP.NET provides In-Process and Out-of-Process state management.
In-Process stores the session in memory on the web server. This requires a "sticky-server" (or
no load-balancing) so that the user is always reconnected to the same web server.
Out-of-Process Session state management stores data in an external data source. The external
data source may be either a SQL Server or a State Server service. Out-of-Process state
management requires that all objects stored in session are serializable.

What is the lifespan for items stored in ViewState? Answer


Item stored in ViewState exist for the life of the current page. This includes postbacks (to the
same page).
ViewState life is limited for Single RoundTrip. Each New postback create new values for
viewstate
What is the transport protocol you use to call a Web service?
SOAP (Simple Object Access Protocol)

Does c# supports destructors? Answer


I think it doesnt allow to use Destructor.There is a method called Dispose() which automatically
calls destructor

Coding for delegates? Answer


using System;
// Declare delegate -- defines required signature:
delegate void SampleDelegate(string message);

class MainClass
{
// Regular method that matches signature:
static void SampleDelegateMethod(string message)
{
Console.WriteLine(message);
}

static void Main()


{
// Instantiate delegate with named method:
SampleDelegate d1 = SampleDelegateMethod;
// Instantiate delegate with anonymous method:
SampleDelegate d2 = delegate(string message)
{
Console.WriteLine(message);
};

// Invoke delegate d1:


d1("Hello");
// Invoke delegate d2:
d2(" World");
}
}

Write code for Factorial? Answer


private void btnCalculae_Click(object sender,
System.EventArgs e)
{
long number = Convert.ToInt64 (txtNumber.Text);
long factorial = 1;
lblFactorial.Text = factorial.ToString
("n20");

// calculate factorial

while ( number > 0 && number <= 20)


{
factorial *= number;
number++;
} // end while loop

txtNumber.Text = "";
txtNumber.Focus();
}

private void btnExit_Click(object sender,


System.EventArgs e)
{
this.Close();
}
}
}
private void btnCalculae_Click(object sender,
System.EventArgs e)
{
string str =txt1.text;
int fact=1;
foreach char c in str
{
fact=convert.toint32(c)*fact;
}
txt2.text=fact;
}

Write code for palindrome? Answer

private bool CheckPalindrome(string myString)

int First;

int Second;

First = 0;

Second = myString.Length - 1;

while (First < Second)

if(myString.Substring(First,1) == myString.Substring
(Second,1))

First ++;

Second --;

}else{

return false;

}
return true;

Or

private bool CheckPalindrome(string myString)


{
string strrevs="";
foreach char c in myString
{
strrevs= c + strrevs;
}

if (strrevs==myString)

return true;
else
return false;
}

What is the difference between finally and dispose methods? Answer


finally will execute after the try block. It must execute if there is any exception caught in the catch
blobk or not.
Dispose method is the last method executed in the c# program
compulsory finally will execute after try and catch block. Dispose method is used to clean up the
objects. Dispose method will call in finally method to clean up the objects

How many catch blocks can be there for a single try block? Answer
There can be any number of catch block for a single try block.
However only the catch block encountered first on the call stack that satisfies the condition for the
exception will be executed for that particular exception, rest will be ingnored.

Which directive is mandatory in page control? <%@ Page %>

How many types of pages. Four types


Master pages, .ASPX, .ASAX, .ASMX, .ASCX

You might also like