Professional Documents
Culture Documents
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
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...).
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
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.
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.
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.
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,
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.
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.
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>
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.
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.
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 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
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.
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!
}
}
}
</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
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;
}
}
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.
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.
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.
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.
}
}
using System;
class Base
{
public Base()
{
Console.WriteLine("Base Constructor Version 1");
}
public Base(int x)
{
Console.WriteLine("Base Constructor Version 2");
}
}
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.
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'.
}
}
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.
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.
using System;
namespace Delegates
{
public delegate int DelegateToMethod(int x, int y);
}
}
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);
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 relational operators can be overloaded,
but only as pairs.
=, . , ?:, ->, 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.
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
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
}
}
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.
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 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.
class MainClass
{
// Regular method that matches signature:
static void SampleDelegateMethod(string message)
{
Console.WriteLine(message);
}
// calculate factorial
txtNumber.Text = "";
txtNumber.Focus();
}
int First;
int Second;
First = 0;
Second = myString.Length - 1;
if(myString.Substring(First,1) == myString.Substring
(Second,1))
First ++;
Second --;
}else{
return false;
}
return true;
Or
if (strrevs==myString)
return true;
else
return false;
}
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.