This blog contains questions generally asked in ASP.Net interviews along with their relevant answers
Thursday, April 9, 2020
Monday, July 27, 2015
What are access modifiers in C#?
Why to use access modifiers?
Modifier
|
Description
|
public
|
There are no restrictions on accessing public members.
|
private
|
Access is limited to within the class definition. This is the default access modifier type if none is formally specified
|
protected
|
Access is limited to within the class definition and any class that inherits from the class
|
internal
|
Access is limited exclusively to classes defined within the current project assembly
|
protected internal
|
Access
is limited to the current assembly and types derived from the
containing class. All members in current project and all members in
derived class can access the variables.
|
public
- Can be accessed by objects of the class
- Can be accessed by derived classes
- Cannot be accessed by object
- Cannot be accessed by derived classes
protected
- Cannot be accessed by object
- By derived classes
- Can be accessed by objects of the class
- Can be accessed by derived classes
- Cannot be accessed by object
- Cannot be accessed by derived classes
- Inherited types, even though they belong to a different assembly, have access to the protected internal members.
- Types that reside in the same assembly, even if they are not derived from the type, also have access to the protected internal members.
Default access
Wednesday, July 22, 2015
What are the differences between Arrays and Collections
- Arrays are fixed in size, therefore once we create an array we are not allowed to increase or decrease its size, based on the requirement. Collections are grow-able, therefore base on our requirement we can increase or decrease its size
- Arrays use more memory space as compared to Collections
- Performance point of view arrays are recommended (Faster), where as collections are not recommended
- Arrays can hold only homogeneous elements, collections can hold both homogeneous and heterogeneous elements
- Arrays can hold both primitives as well as objects, where as collection can not hold primitives (although they can store primitive wrapper classes such as Integer etc)
- In Array , there are no underlined Data Structures, whereas ,Collection has Underlined DS
Monday, December 1, 2014
Difference and Similarities between class and structure?
Class
- Class is a reference type and its object
is created on the heap memory.
- Class can inherit the another class.
- Class can have the all types of
constructor and destructor.
- The member variable of class can be
initialized directly.
- class object can not be created without
using the new keyword, it means we have to use it.
Demo obj=new Demo();
- Structure is a value type that is why its
object is created on the stack memory.
- Structure does not support the
inheritance.
- Structure can only have the parametrized
constructor. it means a structure can not have the non-parametrized
constructor,default constructor and destructor also.
- The member variable of structure can not
be initialized directly.
- Structure object can be created without using the new keyword.(optional)
SIMILARITIES
- Both can have constructors, methods, properties, fields, constants, enumerations,
events, and event handlers. - Structures and classes can implement interface.
- Both can have delegates and events.
What are virtual classes?
When a base class is specified as a virtual base, it can act as an indirect base more than once without duplication of its data members. A single copy of its data members is shared by all the base classes that use it as a virtual base.
When declaring a virtual base class, the virtual keyword appears in the base lists of the derived classes.
Why don’t C# and Java support multiple inheritance? What is wrong with multiple inheritance?
And here is what the code for that example would look like:
class A {
protected:
bool testing;
};
class B: public A { };
class C: public A { };
class D: public B, public C {
public:
void setTesting ( bool xTesting) {
testing = xTesting; // this is uncertain
}
};
In the code above we have the testing data member which is defined by class A. But, the problem is that class D derives from both classes B and C, which both derive from class A. This means that there are essentially 2 copies of the testing flag that are available because there are 2 instances of A in D’s class hierarchy. So, this creates a problem because which copy of the testing flag will be set? And the compiler will give an error and say that the reference to testing in class D is ambiguous.
But, there are some fixes to this problem. One fix is to make it very clear which classe’s version of testing is going to be set:
B :: testing = xTesting; // use B's version of testing
The other fix for this problem is to declare B and C as virtual base classes. This allows only one copy of A to be created for class D, and that clears up any ambiguities.
Alternatives to multiple inheritance
As you can probably see by now, having multiple inheritance built into a language can create problems. So, in the interest of keeping things simple, the creators of Java and C# decided not to allow multiple inheritance. However, there is an alternative to multiple inheritance, known as interfacesWhat is Multiple Inheritance?
Multiple inheritance allows people to create classes that combine aspects of different classes and their corresponding hierarchies. This is something that is quite common because applications often need to use the frameworks of different classes to achieve the desired functionality. Suppose that you are trying to create a class that models the animal known as a Liger, which is the result of having a Tiger and a Lion mate. Then you would create a class called Liger that derives from both the Tiger and Lion classes – so the Liger class would have to use multiple inheritance since it is deriving or inheriting from 2 different classes.
Wednesday, August 6, 2014
Dependency Injection
Dependency injection can be done in three ways.
- Constructor injection
- Method injection
- Property injection
Constructor Injection
In this approach we pass the object of the concrete class into the constructor of the dependent class. So what we need to do to implement this is to have a constructor in the dependent class that will take the concrete class object and assign it to the interface handle this class is using. So if we need to implement this for our
AppPoolWatcher class:class AppPoolWatcher
{
// Handle to EventLog writer to write to the logs
INofificationAction action = null;
public AppPoolWatcher(INofificationAction concreteImplementation)
{
this.action = concreteImplementation;
}
// This function will be called when the app pool has problem
public void Notify(string message)
{
action.ActOnNotification(message);
}
}
In the above code, the constructor will take the concrete class object and bind it to the interface handle. So if we need to pass the EventLogWriter's concrete implementation into this class, all we need to do isEventLogWriter writer = new EventLogWriter();
AppPoolWatcher watcher = new AppPoolWatcher(writer);
watcher.Notify("Sample message to log");
Now if we want this class to send email or sms instead, all we need to do is to pass the object of the respective class in the AppPoolWatcher's constructor. This method is useful when we know that the instance of the dependent class will use the same concrete class for its entire lifetime.Method Injection
So in method injection approach we pass the object of the concrete class into the method the dependent class which is actually invoking the action. So what we need to do to implement this is to have the action function also accept an argument for the concrete class object and assign it to the interface handle this class is using and invoke the action. So if we need to implement this for our AppPoolWatcher class:
class AppPoolWatcher
{
// Handle to EventLog writer to write to the logs
INofificationAction action = null;
// This function will be called when the app pool has problem
public void Notify(INofificationAction concreteAction, string message)
{
this.action = concreteAction;
action.ActOnNotification(message);
}
}
In the above code the action method i.e. Notify will take the concrete class object and bind it to the interface handle. So if we need to pass the EventLogWriter's concrete implementation into this class, all we need to do isEventLogWriter writer = new EventLogWriter(); AppPoolWatcher watcher = new AppPoolWatcher(); watcher.Notify(writer, "Sample message to log");Now if we want this class to send email or sms instead, all we need to do is to pass the object of the respective class in the AppPoolWatcher's invocation method i.e. Notify method in the above example.
Property Injection
So in this approach we pass the object of the concrete class via a setter property that was exposed by the dependent class. So what we need to do to implement this is to have a Setter property or function in the dependent class that will take the concrete class object and assign it to the interface handle this class is using. So if we need to implement this for our AppPoolWatcher class:
class AppPoolWatcher
{
// Handle to EventLog writer to write to the logs
INofificationAction action = null;
public INofificationAction Action
{
get
{
return action;
}
set
{
action = value;
}
}
// This function will be called when the app pool has problem
public void Notify(string message)
{
action.ActOnNotification(message);
}
}
In the above code the setter of Action property will take the concrete class object and bind it to the interface handle. So if we need to pass the EventLogWriter's concrete implementation into this class, all we need to do isEventLogWriter writer = new EventLogWriter();
AppPoolWatcher watcher = new AppPoolWatcher();
// This can be done in some class
watcher.Action = writer;
// This can be done in some other class
watcher.Notify("Sample message to log");
Now if we want this class to send email or sms instead, all we need to do is to pass the object of the respective class in the setter exposed by AppPoolWatcher class. This approach is useful when the responsibility of selecting the concrete implementation and invoking the action are done in separate places/modules. In languages where properties are not supported, there is a separate function to set the dependency. This approach is also known as setter injection. The important thing to note in this approach is that there is a possibility that someone has created the dependent class but no one has set the concrete class dependency yet. If we try to invoke the action in such cases then we should have either some default dependency mapped to the dependent class or have some mechanism to ensure that application will behave properly.
A Note on IoC Containers
All the three approaches we have discussed for dependency injection are ok if we have only one level of dependency. But what if the concrete classes are also dependent of some other abstractions. So if we have chained and nested dependencies, implementing dependency injection will become quite complicated. That is where we can use IoC containers. IoC containers will help us to map the dependencies easily when we have chained or nested dependencies.
What is Inversion of Control?
So if I have to implement inversion of control in the above mentioned problem scenario, the first thing we need to do is to create an abstraction that the higher levels will depend on. So let us create an interface that will provide the abstraction to act on the notification received from
AppPoolWacther.public interface INofificationAction
{
public void ActOnNotification(string message);
}
Now let us change our higher level module i.e. the AppPoolWatcher to use this abstraction rather than the lower level concrete class.
class AppPoolWatcher
{
// Handle to EventLog writer to write to the logs
INofificationAction action = null;
// This function will be called when the app pool has problem
public void Notify(string message)
{
if (action == null)
{
// Here we will map the abstraction i.e. interface to concrete class
}
action.ActOnNotification(message);
}
}
So how will our lower level concrete class will change? how will this class conform to the abstraction i.e. we need to implement the above interface in this class:class EventLogWriter : INofificationAction
{
public void ActOnNotification(string message)
{
// Write to event log here
}
}
So now if I need to have the concrete classes for sending email and sms, these classes will also implement the same interface.
class EmailSender : INofificationAction
{
public void ActOnNotification(string message)
{
// Send email from here
}
}
class SMSSender : INofificationAction
{
public void ActOnNotification(string message)
{
// Send SMS from here
}
}
So the final class design will look like: But there is still one missing piece. When we look at the code of our
AppPoolWatcher,
we can see that it is using the abstraction
i.e. interface but where exactly are we creating the concrete type and
assigning it to this abstraction. To solve this problem, we can do
something like:class AppPoolWatcher
{
// Handle to EventLog writer to write to the logs
INofificationAction action = null;
// This function will be called when the app pool has problem
public void Notify(string message)
{
if (action == null)
{
// Here we will map the abstraction i.e. interface to concrete class
writer = new EventLogWriter();
}
action.ActOnNotification(message);
}
}
But we are again back to where we have started. The concrete class creation is still inside the higher level class. Can we not make it totally decoupled so that even if we add new classes derived from INotificationAction, we don't have to change this class. This is exactly where Dependency injection comes in picture. So its time to look at dependency injection in detail now.
What is Dependency Inversion Principle?
- High-level modules should not depend on low-level modules. Both should depend on abstractions.
- Abstractions should not depend upon details. Details should depend upon abstractions.
What does this definition mean? What is it trying to convey? let us try to understand the definition by looking at examples. A few years back I was involved in writing a windows service which was supposed to run on a Web server. The sole responsibility of this service was to log messages in event logs whenever there is some problem in the IIS application Pool. So what our team has done initially that we created two classes. One for monitoring the Application Pool and second to write the messages in the event log. Our classes looked like this:
class EventLogWriter
{
public void Write(string message)
{
//Write to event log here
}
}
class AppPoolWatcher
{
// Handle to EventLog writer to write to the logs
EventLogWriter writer = null;
// This function will be called when the app pool has problem
public void Notify(string message)
{
if (writer == null)
{
writer = new EventLogWriter();
}
writer.Write(message);
}
}
From the first look, the above class design seems to be sufficient. It looks perfectly good code. But there is a problem in the above design. This design violates the dependency inversion principle. i.e. the high level moduleAppPoolWatcherdepends onEventLogWriterwhich is a concrete class and not an abstraction. How is it a problem? Well let me tell you the next requirement we received for this service and the problem will become very clearly visible.The next requirement we received for this service was to send email to network administrator's email ID for some specific set of error. Now, how will we do that? One idea is to create a class for sending emails and keeping its handle in theAppPoolWatcherbut at any moment we will be using only one object eitherEventLogWriterorEmailSender.The problem will get even worse when we have more actions to take selectively, like sending SMS. Then we will have to have one more class whose instance will be kept inside theAppPoolWatcher. The dependency inversion principle says that we need to decouple this system in such a way that the higher level modules i.e. theAppPoolWatcherin our case will depend on a simple abstraction and will use it. This abstraction will in turn will be mapped to some concrete class which will perform the actual operation.
Thursday, April 5, 2012
What will happen if same method is implemented in two parts of the partial class ?
Saturday, January 28, 2012
What are the types of polymorphism ?
- Static (Compile time): Function Overloading, Operator Overloading
- Dynamic (Run time): Virtual Functions
What is object slicing ?
Example:
Class Base
{
public int i;
};
class Derived : public Base
{
public int j;
};
int main()
{
Base objB;
Derived objD;
objB = objD;
//Here objD contains both i and j.
//But only i is copied to objB.
}
Friday, January 20, 2012
What are partial classes, what is the use of it in .net ?
.Net 2.0 provided us with new feature called partial classes. Using partial classes we can use multiple files to keep the code of same class. Yes - we can put some methods to one file and the others to another file. Although partial classes may be extremely useful they can be also used to ruin system's technical design if developers don't know what happens behind the compiler.
Visual Studio uses partial classes to keep Windows and Web forms automatically generated code separately of user written code behind the forms.
Monday, January 16, 2012
When to use abstract class and when to use interface ?
Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
- If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
- If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
- If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
- If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
A good way to distinguish between a case for the one or the other has always been the following:
1. Are there many classes that can be "grouped together" and described by one noun? If so, have an abstract class by the name of this noun, and inherit the classes from it. (A key decider is that these classes share functionality, and you would never instantiate just an Animal... you would always instantiate a certain kind of Animal: an implementation of your Animal base class)
Example: Cat and Dog can both inherit from abstract class Animal, and this abstract base class will implement a method void Breathe() which all animals will thus do in exactly the same fashion. (I might make this method virtual so that I can override it for certain animals, like Fish, which does not breath the same as most animals).
2. What kinds of verbs can be applied to my class, that might in general also be applied to others? Create an interface for each of these verbs.
Example: All animals can be fed, so I will create an interface called IFeedable and have Animal implement that. Only Dog and Horse are nice enough though to implement ILikeable - I will not implement this on the base class, since this does not apply to Cat.
As said by someone else's reply: the main difference is where you want your implementation. By creating an interface, you can move your implementation to any class that implements your interface.
By creating an abstract class, you can share implementation for all derived classes in one central place, and avoid lots of bad things like code duplication.
What is the difference between abstract class and interface ?
- Classes may inherit from only one base class, so if you want to use abstract classes to provide polymorphism to a group of classes, they must all inherit from that class.
- Abstract classes may also provide members that have already been implemented. Therefore, you can ensure a certain amount of identical functionality with an abstract class, but cannot with an interface.
- An abstract class can contain internal variables but interfaces cannot.
What are Interfaces ?
Interfaces, like abstract classes, cannot be instantiated. An interface can contain a signature of methods properties and indexers. An Interface is a type whose members are all public and abstract by default.
A class implementing the interface must provide the body for the members of the interface. A class can implement more than one interface, contrary to class-inheritance where you can inherit only one class. An interface itself can inherit other interfaces.
We can declare the reference of interface type and it can point to any class implementing it.
It is a convention in C# to prefix the name of interfaces with the uppercase "I" like IDisposable, ISerializable, IEnumerator etc.
What are abstract classes and abstract methods ?
We can declare a reference of type abstract class and it can point to the objects of the classes that have inherited the abstract class
Example:
{
protected double itemprice;
protected double tax;
public abstract double CalculateTax();
public double Tax
{
get { return tax; }
}
public double ItemPrice
{
get { return itemprice; }
}
}
Features of Abstract Class
- An abstract class cannot be instantiated.
- An abstract class contain abstract members as well as non-abstract members.
- An abstract class cannot be a sealed class because the sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.
- A non-abstract class which is derived from an abstract class must include actual implementations of all the abstract members of parent abstract class.
- An abstract class can be inherited from a class and one or more interfaces.
- An Abstract class can have access modifiers like private, protected, internal with class members. But abstract members cannot have private access modifier.
- An Abstract class can have instance variables (like constants and fields).
- An abstract class can have constructors and destructor.
- An abstract method is implicitly a virtual method.
- Abstract properties behave like abstract methods.
- An abstract class cannot be inherited by structures.
- An abstract class cannot support multiple inheritance.
- Don't define public constructors within abstract class. Since abstract class cannot be instantiate and constructors with public access modifiers provides visibility to the classes which can be instantiated.
- Define a protected or an internal constructor within an abstract class. Since a protected constructor allows the base class to do its own initialization when sub-classes are created and an internal constructor can be used to limit concrete implementations of the abstract class to the assembly which contains that class.
