We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Wednesday, July 29, 2015

Interview questions and answers of OOP's Concept in C#

1. What is OOPS?
Object-oriented programming (OOP) is a programming language model organized around objects rather than "actions" and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data, processes it, and produces output data.

2. What is the difference between procedural and object-oriented programming?

Procedural programming is based upon the modular approach in which the larger programs are broken into procedures. Each procedure is a set of instructions that are executed one after another. On the other hand, OOP is based upon objects. An object consists of various elements, such as methods and variables.

3. Can you declare a private class in a namespace?
The classes in a namespace are internal, by default. However, you can explicitly declare them as public only and not as private, protected, or protected internal. The nested classes can be declared as private, protected, or protected internal.

4. Can you declare an overridden method to be static if the original method is not static?

No. Two virtual methods must have the same signature.

5. How can you prevent your class to be inherited further?
You can prevent a class from being inherited further by defining it with the sealed keyword.

6. Can you specify the accessibility modifier for methods inside the interface?

All the methods inside an interface are always public, by default. You cannot specify any other access modifier for them.

7. Can fields inside a class be virtual?
No, Fields inside a class cannot be virtual. Only methods, properties, events and indexers can be virtual.

8. Explain Static Class Members.
Ans: A non-static class can contain static methods, fields, properties, or events.

The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.

Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

9. What are the static constructors and their features?
Static constructors are introduced with C# to initialize the static data of a class. CLR calls the static constructor before the first instance is created.

The static constructor has the following features:

  • No access specifier is required to define it.
  • You cannot pass parameters in a static constructor.
  • A class can have only one static constructor.
  • It can access only static members of the class.
  • It is invoked only once when the program execution begins.
10. Can you allow a class to be inherited, but prevent a method from being overridden in C#?
Yes. Just declare the class public and make the method sealed.

11. What are the different access modifiers?
There are 5 access modifiers. Access modifiers define the scope for members.

  • Private: Accessible only within the class.
  • Protected: - Accessible within the class and in derived classes.
  • internal(Friend):- Accessible anywhere within the current project.
  • protected internal:- Accessible with current project and derived classes.
  • Public: - Accessible everywhere.
12. If we creating an object with parameters, and base class have both constructor default and parameterized, then which constructor of a base class called first.
Ans: Base class default constructor called first.


13. What are the different ways a method can be overloaded?
The different ways to overload a method are given as follows:
  • By changing the number of parameters used
  • By changing the order of parameters
  • By using different data types for the parameters
14. What is the difference between ref & out parameters?
An argument passed as ref must be initialized before passing to the method whereas out parameter needs not to be initialized before passing to a method.

15.can use 'this' in a static method?

We can’t use ‘This’ in a static method because we can only use static variables/methods in a static method.

16. Is it compulsory to override a virtual method?
No. It is optional, not mandatory.

17. Why operator overloading?
Operator overloading permits the use of symbols to represent computations for a type.

18. Can modifiers be part of method signatures?
No.


19. On which argument “params” keyword can be applied?
params keyword can only be applied to the last argument of the method. So the n number of parameters can only be at the end.


20. Explain Design Patterns or What are Design Patterns?
Design patterns are documented tried and tested solutions for recurring problems in a given context. So basically you have a problem context and the proposed solution for the same. Design patterns existed in some or other form right from the inception stage of software development. Let’s say if you want to implement a sorting algorithm the first thing comes to mind is bubble sort. So the problem is sorting and the solution is bubble sort. The same holds true for design patterns.

21. What is a constant variable and read-only variable?
Constant variables are declared and initialized at compile time. The value can’t be changed after wards. Read-only variables will be initialized only from the Static constructor of the class. Read only is used only when we want to assign the value at run time.

22. What are the differences between System.String and System.Text.StringBuilder classes?
System.String is immutable. When we modify the value of a string variable then a new memory is allocated to the new value and the previous memory allocation released. System.StringBuilder was designed to have a concept of a mutable string where a variety of operations can be performed without allocation separate memory locations for the modified string.

23. What is the difference between is and as operators in c#?

  • “is” operator is used to checking the compatibility of an object with a given type and it returns the result as Boolean.
  • “as” operator is used for casting of the object to a type or a class.
24. What are abstract classes? What are the distinct characteristics of an abstract class?
An abstract class is a class that cannot be instantiated and is always used as a base class.
The following are the characteristics of an abstract class:

  • You cannot instantiate an abstract class directly. This implies that you cannot create an object of the abstract class; it must be inherited.
  • You can have abstract as well as non-abstract members in an abstract class.
  • You must declare at least one abstract method in the abstract class.
  • An abstract class is always public.
  • An abstract class is declared using the abstract keyword.
The basic purpose of an abstract class is to provide a common definition of the base class that multiple derived classes can share.

25. A structure in C# can implement one or more interfaces. Is it true or false?

Yes, it is true. Like classes, in C#, structures can implement one or more interfaces.
  • A class can have only one static constructor.
  • It can access only static members of the class.
  • It is invoked only once when the program execution begins.
26. Are private members inherited from base class to derived class?
Ans: Yes.

A derived class has access to the public, protected, internal, and protected internal members of a base class. Even though a derived class inherits the private members of a base class, it cannot access those members. However, all those private members are still present in the derived class and can do the same work they would do in the base class itself. For example, suppose that a protected base class method accesses a private field. That field has to be present in the derived class in order for the inherited base class method to work properly.

27. What are the types of Constructors?

Basically, constructors are 5 types those are:
  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor
  • Static Constructor
  • Private Constructor
28. Differentiate between abstraction and encapsulation.
-Abstraction is design oriented while encapsulation is implementation oriented.

- The focus of abstraction is on the interface i.e. the outside view of the object while encapsulation prevents other objects or methods from looking into the properties and behavior of that object.

29. What is the use of private constructor?

Private constructors are used to preventing creating instances of a class when there are no instance fields or methods, or when a method is called to obtain an instance of a class.
Generally, they are used in singleton design patterns, where the code ensures that only one instance of a class can ever be created

30. What is the syntax to overload an operator?
[<modifiers>] static <type> operator <actualOperator> (<Operand type definitions>)

31. What is the size of an instance of an empty class

In .NET, every instance of a class is allocated on the managed heap and consists of two parts - overhead and data.

The size of the overhead is 8 bytes on a 32-bit system and 16 bytes on a 64-bit system.

The size of the data part is the sum of the bytes required by the individual instance fields of the class plus any padding needed for memory alignment purposes.

Even if there are no instance fields, for technical reasons there still needs to be a way to point into the data part. The CLR, therefore, allocates an additional byte which, for memory alignment reasons, will be effectively increased to 4 bytes on a 32-bit system and 8 bytes on a 64-bit system.

Consequently, an empty class instance will occupy a total of 12 bytes on a 32-bit system or 24 bytes on a 64-bit system.

32. What is an Indexer?
Indexers permit instances of a class or struct to be indexed in the same way as arrays.
Indexers are similar to properties except that their accessors take parameters.
The indexers are usually known as smart arrays in C#.
An indexer also called an indexed property, is a class property that allows you to access a member variable of a class using the features of an array.
Defining an indexer allows you to create classes that act like virtual arrays. Instances of that class can be accessed using the [] array access operator.

33. What is the difference between Abstract Class and Interface?


Abstract Class :

  • Access modifiers are allowed 
  • All methods are abstract 
  • A class can inherit only one abstract class 
  • It cannot be instantiated, which means one cannot make an object of this class. 
  • Can have constructor and destructor 
  • Only one abstract class can be derived 
Interface :
  • We can only define method definition and no implementation. 
  • Access modifiers are not allowed 
  • Some methods can be concrete 
  • A class can inherit many interfaces. 
  • Cannot have constructor and destructor 
  • The class can have multiple interfaces 
34. What are Serialization and Deserialization?
Serialization is a process where we can convert an object state into the stream of bytes. This stream can then be persisted in a file, database, or sent over a network, etc. 

 Deserialization is just vice-versa of serialization where we convert a stream of bytes back to the original object.

35. What is a Constructor chaining?
Overloading the constructor using “this” and “base” keywords so that it overload is called constructor chaining

36. What is a Singleton Class?

A singleton class is such kind of class in which only one object is created throughout the life time of the class. A Singleton class is used when you wish to restrict instantiation of a class to only one object

37. What are the differences between Const & Readonly?

Const

  • Must be initialized at the time of its creation 
  • Used if we want to define something at compile time.
  • Protects from accidentally changing the value of the field 
  • Value is evaluated at compile time. 
  • It can't be static.
  • Initialized at declaration only. 
Read Only
  • Assigned in the constructor and called at Runtime 
  • At Runtime, you can make use of the value 
  • It can be either instance-level or static. 
  • Value is evaluated at run time. 
  • Initialized in the declaration or by code in the constructor 
38. What is a Stack?
A stack is responsible for keeping track of running memory needed in your application. As the name says stack it stacks this memory allocation on the top of the first memory allocation. You can think about stack as series of compartments or boxes put on top of each other. Memory allocation and de-allocation are done using LIFO (Last in first out) logic. In other words, memory is allocated and de-allocated at only one end of the memory i.e. top of the stack. Reference pointers are allocated on the stack. In the end, event clears all the memory variables which are assigned on stack Static Memory – Stack Details stored in stack are Name, Data type and Value of the variable

39. What are Value Types?
Value types are types that hold both data and memory in the same location.
When we assign the ‘int’ value to the other ‘int’ value it creates a completely different copy. These kinds of data types are called ‘Value types’.

  • Value Types in .Net are
  • Double, Float, Integer types (sByte, byte, short, ushort, int, uint, long, ulong, char)
  • Decimal, Bool, Enumeration types
40. What are the Reference Types?
A reference type has a pointer which points to the memory location.

When we create an object and when we assign one object to the other object, they both point to the same memory location. In other words, if we change one of them the other object is also affected this is termed as ‘Reference types’.

Reference Types in .Net: String and Object

41. What are nullable types?

“Nullable types let us store null values inside value type variable.” Normally value type won’t allow us to store null values.

Example: we cannot say

int myVar;
myVar=null;
// It will fail because value types won’t allow null values and “int” is a value type.

string myVar2;
myVar2=null;
It will work because the string is reverence type.

We can say,
Int? myVar;
myVar=null; //Nullable type

42. Why we need Nullable types?
Normally Nullabledatatypes introduced for dealing with issues in two datatypes.

1) DateTime

2) Boolean

One of the two possibilities are there with these variables

1) It may contain some value.
2) It will contain a default value.

Every value type is associated with some default value for an instance for Boolean it is false and for date time its Datetime. Min that is 1/1/0001

Let’s talk about a scenario,
You have retrieved some value from the database
You convert that value into Boolean and store in some variable of type Boolean.
The database may contain null values but your traditional value type cant.
In case null values your variable will contain default values.

It may lead to incorrect operations. The ultimate solution will be using Nullable types which may contain one of the three values,

1) No Value
2) True
3) False


43. When Reflection is useful?
Reflection is useful in the following situations:

  • When you have to access attributes in your program's metadata.
  • For examining and instantiating types in an assembly.
  • For building new types at runtime. Use classes in System.Reflection.Emit.
  • For performing late binding, accessing methods on types created at run time.
44. What is late binding?
Binding is the process of locating the declaration that corresponds to a uniquely specified type. When this process occurs at run time rather than at compile time, it is called late binding.

45. What is Custom Binding?
The common language runtime supports multiple programming languages, and the binding rules of these languages differ. In the early-bound case, code generators can completely control this binding. However, in late binding through reflection, binding must be controlled by customized binding. The Binder class provides custom control of member selection and invocation.
Using custom binding, you can load an assembly at run time, obtain information about types in that assembly, specify the type that you want, and then invoke methods or access fields or properties on that type. This technique is useful if you do not know an object's type at compile time, such as when the object type is dependent on user input.

46. What is Object Pooling?

Object Pooling is something that tries to keep a pool of objects in memory to be reused later and hence it will reduce a load of object creation to a great extent.

47. What are Extension Methods?
“Extension method will let us create new methods for a class without touching that class”.

 Extension methods are mainly useful when we are dealing with Third party libraries. We don’t have the source code of the class but with Extension methods, we will be able to add new member functions into that class.

It makes us obey OCP – Open closed principle, which says “software entities should be closed for modifications but open for extensions. With extension methods, we add new methods to existing classes without modifying it.


 48. What is an Object in OOPS?
An object is an instance of a class. It contains real values instead of variables. For example, let us create an instance of the class Employee called “John”.

Employee John= new Employee();
 Now we can access all the methods in the class “Employee” via object “John” as shown below.

John.setName(“XYZ”);

  • Attribute
  • Behavior
  • Identity
49. What is an Attribute in OOPs?
Attributes define the characteristics of a class.
The set of values of an attribute of a particular object is called its state.
In Class, the Program attribute can be a string or it can be an integer.


50. What is Polymorphism in OOPS?

  • Polymorphism is one of the primary characteristics (concept) of object-oriented programming
  • Poly means many and morph means form. Thus, polymorphism refers to being able to use many forms of a type without regard to the details
  • Polymorphism is the characteristic of being able to assign a different meaning specifically, to allow an entity such as a variable, a function, or an object to have more than one form
  • Polymorphism is the ability to process objects differently depending on their data types
  • Polymorphism is the ability to redefine methods for derived classes.
51. Explain the basic features of OOPs.
The following are the four basic features of OOP:
  • Abstraction - This refers to the process of exposing only the relevant and essential data to the users without showing unnecessary information.
  • Polymorphism - Allows you to use an entity in multiple forms.
  • Encapsulation - Prevents the data from unwanted access by binding of code and data in a single unit called object.
  • Inheritance - Promotes the reusability of code and eliminates the use of redundant code. It is the property through which a child class obtains all the features defined in its parent class. When a class inherits the common properties of another class, the class inheriting the properties is called a derived class and the class that allows inheritance of its common properties is called a base class.
52. What are the Access Modifiers in C#?
Different Access Modifier is - Public, Private, Protected, Internal, Protected Internal
  • Public – When a method or attribute is defined as Public, it can be accessed from any code in the project.
  • Private - When a method or attribute is defined as Private, It can be accessed by any code within the containing class only
  • Protected - When attributes and methods are defined as protected, it can be accessed by any method in the inherited classes and any method within the same class. The protected access modifier cannot be applied to classes and interfaces. Methods and fields in an interface can't be declared protected.
  • Internal – If an attribute or method is defined as Internal, access is restricted to classes within the current project assembly.
  • Protected Internal – If an attribute or method is defined as Protected Internal, access is restricted to classes within the current project assembly and types derived from the containing class.
53.Types of comments in C#?
Single line comments
// for single line comments

Multiple line comments
/* for multi line comments */

XML tags comments

/// XML tags displayed in a code comment

47. What is method overloading?
Method overloading is creating multiple methods with the same name as unique signatures in the same class. When we compile, the compiler uses overload resolution to determine the specific method to be invoked.

54. Can a private virtual method be overridden?
No, because they are not accessible outside the class.

56.. Describe the accessibility modifier “protected internal”.
Protected Internal variables/methods are accessible within the same assembly and also from the classes that are derived from this parent class.

57. What is an object pool in .NET?
An object pool is a container having objects ready to be used. It tracks the object that is currently in use, the total number of objects in the pool. This reduces the overhead of creating and re-creating objects.

58. What is the base class in .net from which all the classes are derived from?
System.Object

59. Can you declare a private class in a namespace?
The classes in a namespace are internal, by default. However, you can explicitly declare them as public only and not as private, protected, or protected internal. The nested classes can be declared as private, protected, or protected internal.

60. Can you declare an overridden method to be static if the original method is not static?
No. Two virtual methods must have the same signature.

61. Can fields inside a class be virtual?
No, Fields inside a class cannot be virtual. Only methods, properties, events and indexers can be virtual.

62. Does .Net Support Multiple Inheritance?
C# doesn't support multiple inheritances. C# & VB.NET supports only multiple types/interface inheritance, i.e. you can derive a class/interface from multiple interfaces. There is no support for multiple implementation inheritance in .NET. That means a class can only be derived from one class.

63.What is the diff between Overriding and Shadowing?
-It is easy to confuse shadowing with overriding. Both are used when a derived class inherits from a base class, and both redefine one declared element with another. But there are significant differences between the two.

You normally use overriding in the following cases:

You are defining polymorphic derived classes.

You want the safety of having the compiler enforce the identical element type and calling sequence.

You normally use shadowing in the following cases:

You anticipate that your base class might be modified and define an element using the same name as yours.

You want the freedom of changing the element type or calling sequence

64. Explain different types of inheritance.
Inheritance in OOP is of four types:
  • Single inheritance - Contains one base class and one derived class
  • Hierarchical inheritance - Contains one base class and multiple derived classes of the same base class
  • Multilevel inheritance - Contains a class derived from a derived class
  • Multiple inheritances - Contains several base classes and a derived class
65. What do you mean by data encapsulation?
· Data encapsulation is a concept of binding data and code in a single unit called object and hiding all the implementation details of a class from the user. It prevents unauthorized access to data and restricts the user to use the necessary data only.

66. A structure in C# can implement one or more interfaces. Is it true or false?
False.

67. What are the different ways a method can be overloaded?
The different ways to overload a method are given as follows:
  • By changing the number of parameters used
  • By changing the order of parameters
  • By using different data types for the parameters

68. What is Inline function?
In the C and C++ programming languages, an inline function is one qualified with the keyword inline; this serves two purposes.
Firstly, it serves as a compiler directive, which suggests (but does not require) that the compiler substitute the body of the function inline by performing inline expansion,
The second purpose of inline is to change linkage behavior; the details of this are complicated.

69. What is this keyword?
Every instance method in every object in C# receives a reference named this when the method is invoked. The reference named this is a reference to the object on which the method was invoked. It can be used for any purpose for which such a reference is needed.

70. In what scenarios will you use an abstract class and in what scenarios will you use an interface?
If you want to increase reusability in inheritance then abstract classes are good. If you want to implement or force some methods across classes must be for uniformity you can use an interface. So to increase reusability via inheritance use the abstract class as it is nothing but a base class and to force methods to use interfaces

71. What is the difference between Object and Instance?
An instance of a user-defined type is called an object. We can instantiate many objects from one class.
An object is an instance of a class.

72. What is a pure virtual function?

When you define only function prototype in a base class without and do the complete implementation in the derived class. This base class is called an abstract class and the client won’t able to instantiate an object using this base class.

A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be pureusing the curious “=0 ” syntax:

class Base
{
public:

void f1();//not virtual
virtual void f2();//virtual, not pure
virtual void f3()=0;//pure virtual
};

73. Define Operator Overloading in C# .net?
We had seen function overloading in the previous example. For operator Overloading, we will have look at the example below. We define a class rectangle with two operator overloading methods.

class Rectangle
{
private int Height;
private int Width;
public Rectangle(intw,int h)
{
Width=w;
Height=h;
}
}
public static bool operator >(Rectangle a,Rectangle b)
{
return a.Height>b.Height ;
}

public static bool operator <(Rectangle a,Rectangle b)
{
return a.Height<b.Height ;
}
}

Let us call the operator overloaded functions from the method below. When first if the condition is triggered, the first overloaded function in the rectangle class will be triggered. When second if the condition is triggered, the second overloaded function in the rectangle class will be triggered.

public static void Main()
{
Rectangle obj1 =new Rectangle();
Rectangle obj2 =new Rectangle();
if(obj1 > obj2){
Console.WriteLine("Rectangle1 is greater than Rectangle2");
}

if(obj1 < obj2)
{
Console.WriteLine("Rectangle1 is less than Rectangle2");
}
}

74. Can there be an abstract class with no abstract methods in it?

Yes, there can be an abstract class without abstract methods.

75. What is the copy constructor?
C# is not providing any copy constructor. But using different ways we can do that. First, we have to create new objects and want to copy all values from an already existing object, for that one we have to write one appropriate method.

No comments: