C# OOPS interview questions for experienced
What is a constructor?
A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor also contains the collection of instructions that are executed at the time of Object creation. Constructors are responsible for object initialization
and memory allocation of its class. If we create any class without a constructor,
the compiler will automatically create one default constructor for that class.
There is always at least one constructor in every class.
Here you need to remember that
a class can have any number of constructors and constructors don’t have any return
type, not even void and within a class, we can create only one static
constructor.
Generally, the constructor name should be the same as the class name. If we want to create a constructor in a class we need to create a constructor method name same as the class name.
class
SampleA
{
public
SampleA()
{
Console.WriteLine("Sample
A Test Method");
}
}
Types of Constructors
Basically constructors are 5 types those are
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor
Default
Constructor
A constructor without having any parameters called
default constructor. In this constructor every instance of the class will be
initialized without any parameter values like as shown below
using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample()
// Default Constructor
{
param1 = "Welcome";
param2 = "dotnet-prasannakumar-putha";
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample(); // Once object of class created
automatically constructor will be called
Console.WriteLine(obj.param1);
Console.WriteLine(obj.param2);
Console.ReadLine();
}
}
}
Parameterized
Constructors:
A constructor with at least one parameter is called
as parameterized constructor. In parameterized constructor we can initialize
each instance of the class to different values like as shown below
using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y) // Declaring Parameterized constructor
with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample("Welcome","Dotnet-prasannakumar-putha"); // Parameterized Constructor Called
Console.WriteLine(obj.param1 +" to "+
obj.param2);
Console.ReadLine();
}
}
}
Constructor
Overloading:
In c# we can overload constructor by creating
another constructor with same method name and different parameters like as shown
below
using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample()
// Default Constructor
{
param1 = "Hi";
param2 = "I am Default Constructor";
}
public Sample(string x, string y) // Declaring Parameterized constructor
with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample(); // Default Constructor will Called
Sample obj1=new Sample("Welcome","Dotnet-prasannakumar-putha"); // Parameterized Constructor will Called
Console.WriteLine(obj.param1 + ",
"+obj.param2);
Console.WriteLine(obj1.param1 +" to " +
obj1.param2);
Console.ReadLine();
}
}
Copy
Constructor:
A parameterized constructor that contains a
parameter of same class type is called as copy constructor. Main purpose of
copy constructor is to initialize new instance to the values of an existing
instance. Check below example for this
using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)
{
param1 = x;
param2 = y;
}
public Sample(Sample obj) // Copy Constructor
{
param1 = obj.param1;
param2 = obj.param2;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample("Welcome", "Dotnet-prasannakumar-putha"); // Create instance to class Sample
Sample obj1=new Sample(obj); // Here obj details
will copied to obj1
Console.WriteLine(obj1.param1 +" to " +
obj1.param2);
Console.ReadLine();
}
}
}
Static
Constructor:
When we declared constructor as static it will be
invoked only once for any number of instances of the class and it’s during the
creation of first instance of the class or the first reference to a static
member in the class. Static constructor is used to initialize static fields of
the class and to write the code that needs to be executed only once.
using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
static Sample()
{
Console.WriteLine("Static Constructor");
}
public Sample()
{
param1 = "Sample";
param2 = "Instance Constructor";
}
}
class Program
{
static void Main(string[] args)
{
// Here Both Static and instance constructors are
invoked for first instance
Sample obj=new Sample();
Console.WriteLine(obj.param1 + " " + obj.param2);
// Here only instance constructor will be invoked
Sample obj1 = new Sample();
Console.WriteLine(obj1.param1 +" " +
obj1.param2);
Console.ReadLine();
}
}
}
Importance
points of static constructor
·
Static constructor will not accept any
parameters because it is automatically called by CLR.
·
Static constructor will not have any
access modifiers.
·
Static constructor will execute
automatically whenever we create first instance of class
·
Only one static constructor will
allowed.
Private
Constructor
Private constructor is a special instance
constructor used in a class that contains static member only. If a class has
one or more private constructor and no public constructor then other classes is
not allowed to create instance of this class this mean we can neither create
the object of the class nor it can be inherit by other class. The main purpose
of creating private constructor is used to restrict the class from being
instantiated when it contains every member as static.
using System;
namespace ConsoleApplication3
{
public class Sample
{
public string param1, param2;
public Sample(string a,string b)
{
param1 = a;
param2 = b;
}
private Sample()
// Private Constructor Declaration
{
Console.WriteLine("Private Constructor with no
prameters");
}
}
class Program
{
static void Main(string[] args)
{
// Here we don't have chance to create instace for
private constructor
Sample obj = new Sample("Welcome","to
Dotnet-prasannakumar-putha");
Console.WriteLine(obj.param1 +" " +
obj.param2);
Console.ReadLine();
}
}
}
In the above method we can create an object of a class with
parameters that will work fine. If create an object of class without parameters it will
not allow us to create.
// it will work fine
Sample obj = new Sample("Welcome","to
Dotnet-prasannakumar-putha");
// it will not work because of inaccessibility
Sample obj=new Sample();
Important
points of private constructor
·
One use of private construct is when we
have only static members.
·
Once we provide a constructor that is
either private or public or any, the compiler will not allow us to add a public
constructor without parameters to the class.
· If we want to create an object of class even if we have private constructors then we need to have a public constructor along with a private constructor
----------------------------------------------------------------------------------------------------------------------------------------
The 4 basics of OOP are encapsulation,
abstraction, inheritance, and polymorphism
Encapsulation:
Encapsulation is a process of binding the data members and
member functions into a single unit.
Abstraction:
Abstraction
is a process of hiding the implementation details and displaying the essential
features.
How to abstract: - By using Access Specifiers
.Net has five access Specifiers
Public --
Accessible outside the class through object reference.
Private --
Accessible inside the class only through member functions.
Protected --
Just like private but Accessible in derived classes also through member
functions.
Internal -- Visible inside the assembly. Accessible through objects.
Protected Internal -- Visible inside the assembly through objects and in
derived classes outside the assembly through member functions.
Inheritance::
Consuming
the members of a class from the other class by establishing a parent-child
relationship
Inheritance
is a process of deriving the new class from an already existing class that allows you
to reuse existing code.
Ex:
Using
System;
Public
class BaseClass
{
Public BaseClass ()
{
Console.WriteLine ("Base Class
Constructor executed");
}
Public void Write ()
{
Console.WriteLine ("Write method
in Base Class executed");
}
}
Public
class ChildClass: BaseClass
{
Public ChildClass ()
{
Console.WriteLine("Child Class
Constructor executed");
}
Public static void Main ()
{
ChildClass CC = new ChildClass ();
CC.Write ();
}
}
C#
supports single class inheritance only. What this means is, your class can
inherit from only one base class at a time. In the code snippet below, class C
is trying to inherit from Class A and B at the same time. This is not allowed
in C#. This will lead to a compile time
public
class A
{
}
public
class B
{
}
public
class C : A, B
{
//error: Class 'C' cannot have multiple base classes: 'A' and 'B'.
}
In C# Multi-Level inheritance is possible.
Using
System;
Public
class A
{
Public void A_Method ()
{
Console.WriteLine ("Class A Method
Called");
}
}
Public
class B: A
{
Public void B_Method ()
{
Console.WriteLine ("Class A Method
Called");
}
}
Public
class C: B
{
Public void C_Method ()
{
Console.WriteLine ("Class A Method
Called");
}
Public static void Main ()
{
C C1 = new C ();
C1.A_Method ();
C1.B_Method ();
C1.C_Method ();
}
}
Are
private class members inherited to the derived class?
Ans:
Yes, the private members are also inherited in the derived class but we will
not be able to access them. Trying to access a private base class member in the
derived class will report a compile-time error.
Using
System;
Public
class A
{
Public
void M1 ()
{
}
Private
void M2 ()
{
}
}
Public
class B: A
{
Public
static void Main ()
{
B B1 =
new B ();
B1.M1
();
//Error,
Cannot access private member M2
//B1.M2
();
}
}
Method Hiding:
The Parent class has a write () method which is available to the child class. In the child class I have created a new write () method. So, now if I create an instance of child class and call the write () method, the child class write () method will be called. The child class is hiding the base class write () method. This is called method hiding.
If we
want to call the parent class write () method, we would have to type cast the
child object to Parent type and then call the write () method as shown in the code
snippet below.
Using
System;
Public
class Parent
{
Public void Write ()
{
Console.WriteLine ("Parent Class
write method");
}
}
Public
class Child: Parent
{
Public new void Write ()
{
Console.WriteLine ("Child Class
write method");
}
Public static void Main ()
{
Child C1 = new Child ();
C1.Write ();
//Type caste C1 to be of type Parent
and call Write () method
((Parent) C1).Write ();
}
}
Polymorphism:
Entity behaving in different forms/ways known as Polymorphism.
When a message can be processed in different ways is called polymorphism. Polymorphism means many forms.
Polymorphism is one of the fundamental concepts of OOP.
Polymorphism provides following features:
It allows you to invoke methods of derived class through base class reference during runtime.
It has the ability for classes to provide different implementations of methods that are called through the same name.
Polymorphism is of two types:
Compile time polymorphism/Overloading
Runtime polymorphism/Overriding
Compile Time Polymorphism
It is an approach of defining multiple methods with the same name changing their signatures known as Compile time polymorphism.
Compile time polymorphism is method and operators overloading. It is also called early binding.
In method overloading method performs the different task at the different input parameters.
Runtime Time Polymorphism
It is an approach of defining multiple methods with the same name and same signatures known as Compile time polymorphism.
Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding.
When overriding a method, you change the behavior of the method for the derived class.
Overloading a method simply involves having another method with the same prototype.
Caution:
Method overloading has nothing to do with inheritance or virtual methods.
Following are examples of methods having different overloads:
void
area(int side);
void
area(int l, int b);
void
area(float radius);
Practical example of Method Overloading (Compile Time Polymorphism)
using System;
namespace
method_overloading
{
class Program
{
public class Print
{
public void display(string name)
{
Console.WriteLine ("Your
name is : " + name);
}
public void display(int age, float
marks)
{
Console.WriteLine ("Your
age is : " + age);
Console.WriteLine ("Your
marks are :" + marks);
}
}
static void Main(string[] args)
{
Print obj = new Print ();
obj.display ("George");
obj.display (34, 76.50f);
Console.ReadLine ();
}
}
}
Note:
In the code if you observe display method is called two times. Display method
will work according to the number of parameters and type of parameters.
When and why to use method overloading:
Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task.
You
should consider overloading a method when you for some reason need a couple of
methods that take different parameters, but conceptually do the same thing.
Things
to keep in mind while method overloading
If you
use overload for method, there are couple of restrictions that the compiler
imposes.
The
rule is that overloads must be different in their signature, which means the
name and the number and type of parameters.
There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name.
Method
Overriding:
Example:
//
Base class
public
class BaseClass
{
public
virtual void Method1()
{
Console.Write("Base
Class Method");
}
}
//
Derived class
public
class DerivedClass : BaseClass
{
public
override void Method1()
{
Console.Write("Derived
Class Method");
}
}
//
Using base and derived class
public
class Sample
{
public
void TestMethod()
{
//
calling the overriden method
DerivedClass
objDC = new DerivedClass();
objDC.Method1();
// calling the baesd class method
BaseClass
objBC = (BaseClass)objDC;
objDC.Method1();
}
}
Output
---------------------
Derived Class Method
Derived Class Method
Why do we need Method Overloading?
If we need to do the same kind of operation in
different ways i.e. for different inputs. In the example described below, we
are doing the addition operation for different inputs. It is hard to find many
different meaningful names for a single action.
Different ways of doing overloading methods-
Method overloading can be done by changing:
The number of parameters in two methods.
The data types of the parameters of methods.
The Order of the parameters of methods.
-----------------------------------------------------------------------------------------------------------------------------
Difference between Abstract Class and Interface in C#
Abstract Class | Interface |
An abstract class can contain methods, fields, constants, constructor, etc. | The interface can only contain signature of methods. |
It contains both declarations and definition part. | It contains only a declaration part. An interface is an empty shell, just only the signatures of the methods. The methods do not contain anything. The interface can't do anything. It's just a pattern |
Multiple inheritances are not achieved by an abstract class. | Multiple inheritances are achieved by the interface. |
It can be fully, partially, or not implemented. | It should be fully implemented. |
It can contain static members. | It does not contain static members. |
It can contain different types of access modifiers like public, private, protected, etc. | It only contains public access modifier because everything in the interface is public. |
A class can only use one abstract class. | A class can use multiple interface. |
But if we add a new method to an abstract class then we have the option of providing a default implementation and therefore all the existing code might work properly. | If we add a new method to an An interface then we have to track down all the implementations of the interface and define implementation for the new method. |
The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
----------------------------------------------------------------------------------------------------------------------------
What is a static class in c# for example?
· In C#, static means something which cannot be
instantiated. Static classes are sealed and therefore cannot
be inherited. Static classes are sealed which means you cannot inherit a static class from
another class.
- You cannot create an object of a static class and cannot access static members using an object. Therefore the members of the static class can be accessed directly using a class name like ClassName.MemberName.
Static class members can be accessed using ClassName.MemberName.
·
Static methods can be called without creating an object.
- All the members of a static class must be static;
otherwise, the compiler will give an error.
- A static class can contain static variables, static
methods, static properties, static operators, static events, and static
constructors.
- A static class cannot contain instance members and
constructors.
- Indexers and destructors cannot be static
- A static class cannot inherit from other classes.
·
They cannot inherit from any class except Object.
·
Static classes cannot contain an instance constructor.
·
However, they can contain a static constructor.
Static Members in
Non-static Class:
·
The normal class (non-static class) can contain one or more
static methods, fields, properties, events, and other non-static members.
· It is more practical to define a non-static class with some static members than to declare an entire class as static.
Static Fields
Static fields in a non-static class can be defined using the static keyword.
Static fields of a non-static class are shared across all the instances. So, changes done by one instance would reflect in others.
Advantages of Static
Classes
- If you declare any member as a non-static member, you
will get an error.
- When you try to create an instance to the static class,
it again generates a compile-time error, because the static members can be
accessed directly with its class name.
- The static keyword is used before the class keyword in a
class definition to declare a static class.
- Static class members are accessed by the class name
followed by the member name.
- The advantage of a static class is that it provides you
guarantee that instances of the static class cannot be created.
- C# static class cannot contain instance constructor
When should you go for a static class? Typically
you can implement helper or utility classes as static classes since they don’t
need to be instantiated or inherited and generally contain a collection of some
reusable methods and properties. The following code listing illustrates what a
static class in C# looks like.
When a variable is
declared as static, then a single copy of the variable is created
and shared among all objects at the class level. Static variables are accessed with the name of
the class, they do not require any object for access.
----------------------------------------------------------------------------------------------------------------------------
Difference between static members and non-static members
·
When a class member includes a static modifier, the member
is classed as a static member.
·
When no static modifier is present the member is called a
non-static member or instance member.
·
Static members are invoked using the class names, whereas
instance members are invoked using instances (objects) of the class.
---------------------------------------------------------------------------------------------------------------------------
Static constructor:
- The static constructor is defined using the static keyword
and without using access modifiers public, private, or protected.
·
A static constructor is used to initialize the static
members of a class. The static constructor of a class is invoked the first time
a static member of the class is accessed.
- A non-static class can contain one parameterless static constructor. Parameterized static constructors are not allowed.
- Static constructors will be executed only once in their lifetime. So, you cannot determine when it will get called in an application if a class is being used at multiple places.
- A static constructor can only access static members. It
cannot contain or access instance members.
·
The static constructor is called only once whenever the static method is used or creating an instance for the first time.
·
They are used to initialize the static fields in a class.
·
You declare a static constructor by using the static in
front of the constructor name
·
They are called only once, no matter how many instances you
create.
·
Static constructors are called before the instance
constructors.
Example
of Constructor
class
C
{
private int x;
private int y;
public C (int i, int j)
{
x = i;
y = j;
}
public void display ()
{
Console.WriteLine(x +
"i+" + y);
}
}
Example
of Destructor
class
D
{
public D ()
{
// constructor
}
~D ()
{
// Destructor
}
}
-----------------------------------------------------------------------------------------------------------------------------
C#
| Sealed Class:
Sealed classes are used to restrict the users from
inheriting the class. A class can be sealed by using
the sealed keyword. The keyword tells the compiler
that the class is sealed, and therefore, cannot be
extended. No class can be derived from a sealed
class.
The following is the syntax of a sealed class :
sealed class class_name
{
// data
members
// methods
}
A method can also be sealed, and in that case, the
method cannot be overridden. However, a method can be sealed in the classes in
which they have been inherited. If you want to declare a method as sealed, then
it has to be declared as virtual in its base class.
//
Sealed class
sealed class SealedClass {
//
Calling Function
public
int Add(int a, int b)
{
return
a + b;
}
}
class Program {
//
Main Method
static
void Main(string[] args)
{
//
Creating an object of Sealed Class
SealedClass slc = new SealedClass();
//
Performing Addition operation
int
total = slc.Add(6, 4);
Console.WriteLine("Total
= " + total.ToString());
}
}
Consider the following example of a sealed method in a derived class :
// C# program to
// define Sealed Class
using System;
class Printer {
// Display
Function for
//
Dimension printing
public
virtual void show()
{
Console.WriteLine("display dimension : 6*6");
}
// Display Function
public
virtual void print()
{
Console.WriteLine("printer printing....\n");
}
}
// inheriting class
class LaserJet : Printer {
// Sealed
Display Function
// for
Dimension printing
sealed
override public void show()
{
Console.WriteLine("display dimension : 12*12");
}
//
Function to override
// Print()
function
override
public void print()
{
Console.WriteLine("Laserjet printer printing....\n");
}
}
// Officejet class cannot override show
// function as it is sealed in LaserJet class.
class Officejet : LaserJet {
// cannot
override show function or else
//
compiler error : 'Officejet.show()' :
// cannot
override inherited member
//
'LaserJet.show()' because it is sealed.
override
public void print()
{
Console.WriteLine("Officejet printer printing....");
}
}
// Driver Class
class Program {
// Driver
Code
static
void Main(string[] args)
{
Printer p = new Printer();
p.show();
p.print();
Printer ls = new LaserJet();
ls.show();
ls.print();
Printer of = new Officejet();
of.show();
of.print();
}
}
Why Sealed Classes?
Sealed class is used to stop a class to be
inherited. You cannot derive or extend any class from it.
The sealed method is implemented so that no other class
can overthrow it and implement its own method.
The main purpose of the sealed class is to withdraw
the inheritance attribute from the user so that they can’t attain a class from
a sealed class. Sealed classes are used best when you have a class with static
members.
e.g the “Pens” and “Brushes” classes of the
System.Drawing namespace. The Pens class represents the pens for standard
colors. This class has only static members. For example, “Pens. Red” represents
a pen with red color. Similarly, the “Brushes” class represents standard
brushes. “Brushes. Red” represents a brush with red color.
-----------------------------------------------------------------------------------------------------------------------------
Q)Why a private virtual method cannot be overridden
in C#?
Because private virtual methods are not accessible
outside the class.
-----------------------------------------------------------------------------------------------------------------------------
What is Singleton's design pattern in C#?
Singleton design pattern in C# is a common design
pattern. In this pattern, a class has just one instance in the program that
gives global access to it. Or we can say that a singleton is a class that
permits only one instance of itself to be made and usually gives simple access
to that instance.
There are different approaches to carry out a
singleton design in C#. Coming up next are the regular attributes of a
singleton design.
Private and parameterizes single constructor
Sealed class.
Static variable to hold a reference to the single
made example
A public and static method of getting the reference
to the made example.
We can implement a singleton design pattern in C#
using:
No Thread Safe Singleton.
Thread-Safety Singleton.
Thread-Safety Singleton using Double-Check Locking.
Thread-safe without a lock.
Using .NET 4’s Lazy<T> type.
-----------------------------------------------------------------------------------------------------------------------------
In C#, both abstract classes and interfaces are used to define contracts and provide a way to implement polymorphism. However, there are some differences between them, and their usage depends on the specific scenario. Here are some guidelines for when to use an abstract class and when to use an interface:
Use an abstract class when:
· You want to provide a common base implementation: Abstract classes can include method implementations, fields, and properties. This allows you to define common behavior and state that derived classes can inherit and override as needed.
· You want to provide default implementations: Abstract classes can have method implementations that can be inherited by derived classes. This can be useful when you want to provide default behavior but also allow derived classes to override it if necessary.
· You want to define shared data: Abstract classes can have fields and properties that are shared among derived classes. This can be useful when you want to provide a common state or data that all derived classes should have.
Use an interface when:
· You want to define a contract: Interfaces define a contract that classes can implement. They specify a set of methods, properties, and events that a class must implement. This is useful when you want to enforce a specific behavior across multiple classes without providing any implementation details.
· You want to support multiple inheritances: C# does not support multiple inheritances of classes, but a class can implement multiple interfaces. If you need a class to have behavior from multiple sources, interfaces are the way to go.
· You want to provide a level of abstraction: Interfaces allow you to program against abstractions rather than concrete implementations. This can make your code more flexible and decoupled, as you can work with different implementations of an interface without relying on specific classes.
In general, if you need to provide a base implementation or shared data, use an abstract class. If you want to define a contract or support multiple inheritance, use an interface. It’s also possible to use a combination of both, depending on your requirements.
-------------------------------------------------------
Comments
Post a Comment