Monday 17 February 2014

C#.NET - Object Oriented Programming interview questions with answers - Part 2

Hi All, I researched on .NET and collected important interview questions on C#.NET Object Oriented Programming. 
I am posting interview questions with answers parts by parts.


Please Find Other Interview Questions

C#.NET - Object Oriented Programming interview questions with answers - Part 1

C#.NET - Object Oriented Programming interview questions with answers - Part 3

What is static readonly fields?
-It is very suimilar to the constant fields.
- static readonly variables cannot assign value at complie time initilization.
- value will be assigned at runtime through the static constructor.
Note: Only the C# built-in types except System.Object may be declared as const.
Note: Use defined types classes, arrays and structs cannot be constant.
Note: Constants must be initialized at the time of declaration.
Note: You cannot intilize implicit typed local variable to the null
Ex: var name=null;
What is extension method? Explain about extension methods?
Extension methods enables you to add new methods to the existing type.
Extension methods are special kind of static methods but they are called as instance method.
Examples of extension methods are System.Collections.IEnumerable and System.Collections.Generic.IEnumerable types.
If you are using the extension methods in your code you should refer the namespace into your program.
Ex: To use extension methods of System.Collections.IEnumerable and System.Collections.Generic.IEnumerable types you should refer the using system.Linq namespace.
If your extension method has the same signature of the method inside the type your extension method will never called.
Can we implement an extension method in a non-static class?
No, you should implement an extension method inside the static class.
What are named arguments?
Instead of passing arguments in parameters position you can pass the arguments by using the parameters name.
Ex:
GetTotal(number1: 10, number2: 20)
GetTotal(number2: 20, number1: 10)
What are optional parameters?
You can omit the arguments for the optional parameters.
Compailor will take default values for the optional parameters.
Ex:
OptionalMethod(string required, int optional = 10)
You can call this method as follows
OptionalMethod("name", 30);
OptionalMethod("name");
What are constructors?
Constructors are called when you instantiate the class or struct.
Constructors have the same name as class or struct.
Used to set the default values of the data members of class or struct.
You can limit the class from instantiating.
Both class and struct allows multiple constructors with different arguments.
How could you prevent a class from instantiating?
We can prevent a class from instantiating by making constructor as private.
Note: structs cannot contain the default parameterless constructor because compiler automatically provide one.
How can you call the base constructor from the child constructor?
You can call it by using the base keyword.

public Manager():base()
{
}
In the derived class if you are not calling the base class constructor explicitly by using the base keyword compiler will call internally base class constructor using the base keyword like above program.
Note: To initialize a static class or a static fields you must create a static constructor.
Note: It is better to make data members as private because if you make them as public anyone can access it from outside. So, protect data members by making them as private and initialize them through the properties and make properties as public.
What is a default constructor?
A constructor which is not have any arguments.
Note: If your class doesn't have any default constructor. a default constructor will automatically generates and assign default values to the data members.
Note: All C# types including premitive types such as int and double, inherit from a sigle base Object type.
Note: Assemblies contains the executable code in the form of IL code, and symbolic information in the form of metadata.
What is the default access level of constructor?
private
Note: Generally private constructors used in the classes that contains the static members only. Like Math class. Match class have static members and methods.
Note: We can use a private constructor to initialize the static members of the class.
Can you inherit the class which is have the private constructor?
No, you cannot.
In which type of situations we use private constructors?
If you want to prevent the user from instantiating the class we can use private constructor.
In which situtation you will use static constructor?
Generally in the situation when you want to initialize the static data of the class.
Explain about destructor?
Destructor is used to released the instances of the class.
Structs doesnt support the destructors.
A class should have only one destructor.
Destructor will call automatically by the garbage collector.
Destructor cannot be overloaded and inherited.
Destructor doesn't have modifiers as well as parameters.
Destructor internally call the Finalize() method.
What Object initializers do?
Object initializers allows us to access the fields and properties of the class at the time of the object creation. Instead of declaring the parametarised constructor in the class to assign the values to the fields and properties we can use the Object initializers.
Note: While you initializing data to the members of the class using object initilizers compiler will call the default constructor of the class.
So, If a class have the private default constructor object initializers will give the compile time error.
What is a Nested Type?
A type wich is declared under the class or the struct.
By default nested types are private.
You can get all the parent type members inside the nested type.
You can create the object of the nested type as follows.
Parent.Nested obj=new Parent.Nested();
Note: Partial method declaration must starts with the contextual keyword and must return the void.
Partial methods cannot be virtual.
Partial methods can be static.
Explain Anonymous Types?
Anonymous types are introduced in C# 3.0.
These are the datatypes generated at runtime by the compiler.
These are helpful in LINQ queries.
EX:
var employees=from employee in Employees
select new {employee.Name, employee.Salary}
Instead of selecting the whole properties of the employee we can select few of them.
Note: Value types donnot allow inheritance
Note: ?? operator used to compare with nullable types.
Note: Static methods cannot be inherited or oveerriden.
Explain about partial method?
Partials methods are defined their signature in once partial type and implemented in another partial type.
If partial method has no implementation the compiler will remove the partial method from the class at compile time.

Paritial methods are always private.
Partial methods must return void.
In both signature and implemtation signature should match.
Assume two interfaces have one method with same name and return type.

interface IInterface1
{
void Method1();
}
interface IInterface2
{
void Method1();
}
you are inheriting those two interfaces into one class.

class Program:IInterface1,IInterface2
{
}
How can you implement those methods in your derived class and how can you call the respected methods of interfaces?
interface IInterface1
{
void Method1();
}
interface IInterface2
{
void Method1();
}
class Program:IInterface1,IInterface2
{
static void Main()
{
IInterface1 aa = new Program();
aa.Method1();
IInterface2 aa2 = new Program();
aa2.Method1();
}

void IInterface1.Method1()
{
Console.WriteLine("Methods of IInterface1");
}
void IInterface2.Method1()
{
Console.WriteLine("Methods of IInterface2");
}
}

// Output
// Methods of IInterface1
// Methods of IInterface2
What is encapsulation?
Wrapping up of a data into a single unit (i.e. class) is called encapsulation.

It is a technique to hide the internal members of a class.

We can hide the private information and we can show the public information using encapsulation.
EX: hiding the properties and exposing the property to access the private data.
Note: If your class have only parameterised constructors and you are you are trying to instantitiate the class with out the parameters the compiler won't allow to create it.
for that you shold explicitly define the default constructor.
How can you call the local constructor from another constructor?
using this keyword.
Ex:
public Employee()
{
//...............
}
public Employee(string name):this()
{

}
What is instance constructor?
A constructor which is used to initialize the instance members of the class.
Note: Data members should be private and should be access only through the class methods and functions.
Note: To initialize a static class or a static fields you must create a static constructor.
Note: It is better to make data members as private because if you make them as public anyone can access it from outside. So, protect data members by making them as private and initialize them through the properties and make properties as public.
What is a default constructor?
A constructor which is not have any arguments.
Note: If your class doesn't have any default constructor. a default constructor will automatically generates and assign default values to the data members.
Note: All C# types including premitive types such as int and double, inherit from a sigle base Object type.
Note: Assemblies contains the executable code in the form of IL code, and symbolic information in the form of metadata.
What is the default access level of constructor?
private
Note: Generally private constructors used in the classes that contains the static members only. Like Math class. Match class have static members and methods.
Note: We can use a private constructor to initialize the static members of the class.
Can you inherit the class which is have the private constructor?
No, you cannot.
In which type of situations we use private constructors?
If you want to prevent the user from instantiating the class we can use private constructor.
In which situtation you will use static constructor?
Generally in the situation when you want to initialize the static data of the class.
Explain about destructor?
Destructor is used to released the instances of the class.
Structs doesnt support the destructors.
A class should have only one destructor.
Destructor will call automatically by the garbage collector.
Destructor cannot be overloaded and inherited.
Destructor doesn't have modifiers as well as parameters.
Destructor internally call the Finalize() method.
What Object initializers do?
Object initializers allows us to access the fields and properties of the class at the time of the object creation. Instead of declaring the parametarised constructor in the class to assign the values to the fields and properties we can use the Object initializers.
Note: While you initializing data to the members of the class using object initilizers compiler will call the default constructor of the class.
So, If a class have the private default constructor object initializers will give the compile time error.

Wednesday 12 February 2014

C#.NET - Object Oriented Programming interview questions with answers - Part 1

Hi All, I researched on .NET and collected important interview questions on C#.NET Object Oriented Programming. 
I am posting interview questions with answers parts by parts.


Please Find Other Interview Questions

C#.NET - Object Oriented Programming interview questions with answers - Part 2

C#.NET - Object Oriented Programming interview questions with answers - Part 3


What is wrong in the following program?
static void Main()
{
    // Array initialization.
    var numbers = {10,20,30 };
    foreach (var item in numbers)
    {
        Console.WriteLine(item);
    }
}
Compile time Error "Cannot initialize an implicitly-typed local variable (numbers) with an array initializer ({10,20,30 })". Can only use array initializer expressions to assign to array types. Try using a new expression instead.

var numbers = new int[]{10,20,30 };
What are the class members.
Fields
Constants
Properties
Methods
Constructors
Destructors
Events
Indexers
Operators
Nested Types.
What is the default access modifier of the class?
If the class is nested under another class then the default access modifier is private. Otherwise the default access modifier is internal.
Does structs supports inheritance?
structs doesn't support the inheritance through the classes but structs supports the inheritance through the interfaces.
Can we declare structs as static?
No
Can we create an object for the static class?
No, you can’t create.
Does static class contain the non-static methods?
No, a static class should contain the static methods and fields.
How many static class copies will load into the program when the program loads?
Only one.
Can a struct nested under class?
Yes
Can a class nested under struct?
Yes
What is the main benefit of object initializers?
You can instantiate and initialize class or struct objects, and collections of objects, without explicitly calling their constructor.
What is a class?
A class is user defined type. It defines the data and behavior of the type. Class has the following members. Fields
Constants
Properties
Methods
Constructors
Destructors
Events
Indexers
Operators
Nested Types.
What is the output of the following program?
class A
{
public string mobileNumber { get; set; }
}
class Program
{
static void Main()
{
A obj1 = new A();
obj1.mobileNumber = "9999999999";
A obj2 = obj1;
obj1.mobileNumber = "8888888888";
Console.WriteLine(obj2.mobileNumber);
}
}
8888888888
Because, here we are creating two reference objects and both are referring to the same object. If any changes are made to the object (obj1) will be reflect to the object2 also.
What is the difference between the struct instances and class instances?
Class instance will refer to the address of the object which is on the managed heap (Memory allocated on managed heap). Struct instance hold the entire copy of the object. (Memory allocated on stack)
What is the difference between == and .Equals() ?
If you want to determine two class instances refering the one object in heap memory(Means they have the same identity) use the static Equals method.
Can we initialize the fields inside the struct?
Fields cannot be initialized under struct declaration unless they are declared as const or static.
Can a struct allow default constructor or destructor?
No
What is the output of the following program?
public struct Employee
{
public string address { get; set; }
}
class Program
{
static void Main()
{
Employee e1 = new Employee();
e1.address = "Hyderabad";
Employee e2 = e1;
e1.address = "Secundrabad";
Console.WriteLine(e2.address);
}
}
Hyderabad Because when a struct is assigned to the new variable entire struct will be copied to that variable. If you modify the assigned variable it won't effect on other variable.
Does a struct allow parameterized constructor and parameterized destructor?
Yes
What are the possible ways to instantiate the struct?
Unlike class we can instantiate the structs by using the new keyword or without the new keyword.

public struct Employee
{
public string name;
}
class Program
{
static void Main()
{
Employee e1 = new Employee();
e1.name = "Srinubabu Ravilla";
Employee e2;
e2.name = "Ramakrishna Pouduri";
}
}
What is Inheritance?
Inheritance allows you to reuse, extend and modify the behavior of the base class.
When you derive a base class into the derived class all the members of the base class will be derived into the derived class except constructor and destructor of the base class.
Why we declare some methods in base class as virtual?
OR
What is virtual method?
When a method is declared as virtual it should be override in the derived class.
Can we instantiate abstract classes?
No you can’t instantiate the abstract classes. You can instantiate a derived class which is deriving the abstract class.
Is interface is value type and reference type?
Reference type.
What is an Interface?
Interface is a reference type. Interface is similar like abstract classes but interface contains only abstract members. The class which is deriving the interface should implement all the members of the interface. Interface supports the multiple inheritance.
How can you prevent a class from inheriting?
Make a class as sealed.
What is the use of base keyword?
The base keyword is use to access the members of the base class from within a derived class.

Without base keyword.

public class BaseClass
{
public virtual void Print()
{
Console.WriteLine("Base class method called.");
}
}
class Program:BaseClass
{
public override void Print()
{
Console.WriteLine("Derived class method called.");
}
static void Main()
{
Program p = new Program();
p.Print();
}
}
Output:
Derived class method called.

With base keyword.

public class BaseClass
{
public virtual void Print()
{
Console.WriteLine("Base class method called.");
}
}
class Program:BaseClass
{
public override void Print()
{
base.Print();
Console.WriteLine("Derived class method called.");
}
static void Main()
{
Program p = new Program();
p.Print();
}
}
Output:
Derived class method called.
Base class method called.
How can you call the base class constructor from the derived class constructor?
By using the base keyword we can call the base class constructor from the derived calss.
What is the purpose of the keyword in C#?
To avoid naming conflicts.
To pass an object as a parameter to the other method.
Indexers.
In .NET every Type is polymorphic because all types are inherited from Object.
1) True
2) False
True.
Can we declare a method as an override in derived which was declared as virtual in base class?
Yes
Which type of methods in base class you override in the derived class?
The methods which are declared as virtual and abstract in base class.
Can you declare fields as declared virtual in base class?
No, Only methods, properties, events and indexers can be virtual.
How can you hide the base calss members in the derived class?
By using the new keyword you can hide the base class members. But you can access the base class members in the derived class. If you want to access the base class members cast the derived class object into the base class object.
EX:
public class BaseClass
{
public void Call()
{
Console.WriteLine("Base Class");
}
}
public class DerivedClass : BaseClass
{
public new void Call()
{
Console.WriteLine("Derived Class");
}
}
class Program
{
static void Main()
{
DerivedClass objB = new DerivedClass();
objB.Call(); // Base class method will call.

BaseClass objA = (BaseClass)objB;
objA.Call(); // Derived class method will call.
}
}

Output:
Base Class
Derived Class
Which type of methods can you override?
The methods which are declared as
virtual
abstract
override
How can you prevent a method from overriding?
By uisng the sealed keyword.
public sealed override void Print()
{

}
What is the output of the following program?

public class A
{
public void WhoAreYou() {
Console.Write("A");
}
}
public class B : A
{
public new void WhoAreYou() {
base.WhoAreYou();
Console.Write("B");
}
}
public class C : B
{
public new void WhoAreYou() {
Console.Write("C");
base.WhoAreYou();
}
}
public class D : C
{
public new void WhoAreYou() {
base.WhoAreYou();
Console.Write("D");
}
}
class Program
{
static void Main()
{
A obj1 = new A();
obj1.WhoAreYou();
B obj2 = new B();
obj2.WhoAreYou();
A obj3 = new B();
obj3.WhoAreYou();
C obj4 = new C();
obj4.WhoAreYou();
D obj5 = new D();
obj5.WhoAreYou();
}
}

1) AABACABCADB
2) AABACDBCADB
3) AABCCABCADB
4) AABACABCADB
4
What is the benefit of the new keyword in C#?
We can hide the base class virtual methods.
What is the output of the following program?

public class A
{
public virtual void Print(int virtualPrint)
{
Console.WriteLine("Virtual method.");
}
}
public class B : A
{
public override void Print(int overridePrint)
{
Console.WriteLine("Override method.");
}
public void Print(double derivedPrint)
{
Console.WriteLine("Derived class method.");
}
}
class Program
{
static void Main()
{
B obj = new B();
obj.Print(120);
((A)obj).Print(120);
}
}
Derived class method.
Override method.
What is the relationship of override and new modifiers with the virtual method?
override modifier extends the base class virtual method.
new modifier hides the base class virtual method.
Can i use both new and override modifiers on class member?
No, You can't use both on a single class member. Because, new modifier hides the original method and override modifier extends the implementation of the original method.
What is the output for the following program?

class Program
{
static void Main(string[] args)
{
ClassA bcdc = new ClassB();
bcdc.Method1();
bcdc.Method2();
}
}
class ClassA
{
public virtual void Method1()
{
Console.WriteLine("ClassA - Method1");
}
public virtual void Method2()
{
Console.WriteLine("ClassA - Method2");
}
}
class ClassB : ClassA
{
public override void Method1()
{
Console.WriteLine("ClassB - Method1");
}
public new void Method2()
{
Console.WriteLine("ClassB - Method2");
}
}
ClassB - Method1
ClassA - Method2
What is an abstract class?
Abstract classes create by using the abstract keyword.
Abstract classes have the abstract members as well as non-abstract members.
You can’t create an instance of the abstract class.
You should derive it and implement all the abstract members inside the derived class.
How to prevent a class from inheritance?
By making the class a sealed.
What is an abstract method?
A method which doesn't implement the body is called abstract method. Derived class of the abstract class must implement all abstract methods of the abstract class.
Can we make abstract method as virtual?
No, all abstract methods are already virtual by default.
Can we make sealed class as abstract class?
No, sealed classes prevent the class from inheriting but abstract class is support for deriving so you can't make a sealed class as an abstract class.
What is a static class?
Contains only static members.
Can't be instantiate.
Is sealed (cannot support inheritance).
Cannot contain instance constructors.
Access the members of the static class by using the class name.
How many times a static constructor called in the application?
Only once.
What is a private constructor? What is the use of it?
A constructor which is declared as private is a private constructor.
You cannot instantiate the class which have the private constructor. So, a private constructor prevents the class from instantiating.
Can a non-static class contain the static members?
Yes, a non-static class can contain static members as well as instance members
Can we declare a constant field as static?
No, constant field is by default static.
What is the main use of the static classes?
You can declare a static class globally. A static class will be load when the program runs and application have only one copy of static class and it is globally available for the application. We can use it in entire the application.
Can we access private members of the base class in derived class?
No, You cannot. Because, When you derive the base class all members of the base class will be derived into the derived class. But you cannot access the private members of the base class.
How many ways you can assign a value to the read only field?
Two ways
During the initialization (or) through the constructor.
Can we change the value of the constant field at runtime?
No you cannot.
What is the access level of the public modifier?
Can access the members of the class/struct in the same assembly or the assembly which is refering it.
What is the access level of the private modifier?
Can access the members of the class/struct with in the same class /struct.
What is the access level of the protected modifier?
Can access the members of the struct/class with in the class or struct, and can access the class which is derives from that class.
What is the access level of the internal modifier?
Can access the members of the class/struct with in the assembly.
What is the access level of the protected internal modifier?
Can access the the members of the class/struct with in the class/strcut, with in the class/struct that are derived from it and within the assembly.
"Structs cannot declare as protected" is this correct? Explain why?
We cannot declare the structs as protected because structs doesn't support the inheritance.
Can we declare the destructors as public?
No, you should not use any modifier on the destructors.
Can we add access specifies to the interface members?
No, you cannot.
Because interface members are always public. Because the interface main purpose is to derive the members and implement them.
Note: Don't make a class field as public instead use private or protected it is recommended.
Please Find C#.NET - Object Oriented Programming interview questions with answers - Part 2