Search This Blog

Wednesday, June 20, 2018

Oops Interview Question - 2


 26. What is the difference between Finalize() and Dispose() methods?
Dispose() is called when we want for an object to release any unmanaged resources with them. On the other hand Finalize() is used for the same purpose but it doesn’t assure the garbage collection of an object.
The finalizer method is called when your object is garbage collected and you have no guarantee when this will happen (you can force it, but it will hurt performance).

The Dispose method on the other hand is meant to be called by the code that created your class so that you can clean up and release any resources you have acquired (unmanaged data, database connections, file handles, etc) the moment the code is done with your object.
Dispose
Finalize
It is used to free unmanaged resources like files, database connections etc. at any time.

It can be used to free unmanaged resources (when you implement it) like files, database connections etc. held by an object before that object is destroyed.

Explicitly, it is called by user code and the class which is implementing dispose method, must has to implement IDisposable interface.

Internally, it is called by Garbage Collector and cannot be called by user code.

It belongs to IDisposable interface.

It belongs to Object class.

It's implemented by implementing IDisposable interface Dispose() method.

It's implemented with the help of destructor in C++ & C#.

There is no performance costs associated with Dispose method.

There is performance costs associated with Finalize method since it doesn't clean the memory immediately and called by GC automatically.

27. What are circular references?
Circular reference is situation in which two or more resources are interdependent on each other causes the lock condition and make the resources unusable.
Circular dependency is a situation where “classlibrary1” references “classlibrary2” and “classlibrary2” is trying to reference “classlibrary1”.
If you ever try to reference class libraries with each other, Visual Studio throws the below exception.
Circular dependency problem can be overcome by using interfaces or events. So for the above problem, we can introduce an interface in between the “MiddleTier” and “Dal”.



So below is the solution. You can create an altogether different C# project and create an interface “ICustomer” as shown in the below code:
Circular dependency is a sign of bad design and tight coupling. So when you get into a circular dependency situation rather than fixing it directly by interfaces or events, question yourself why you landed in this situation.

28. What are generics in C#.NET?
Generics are used to make reusable code classes to decrease the code redundancy, increase type safety and performance. Using generics, we can create collection classes. To create generic collection, System.Collections.Generic namespace should be used instead of classes such as ArrayList in the System.Collections namespace. Generics promotes the usage of parameterized types.
// Declare the generic class.
public class GenericList<T>
{
    public void Add(T input) { }
}
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int.
        GenericList<int> list1 = new GenericList<int>();
        list1.Add(1);

        // Declare a list of type string.
        GenericList<string> list2 = new GenericList<string>();
        list2.Add("");

        // Declare a list of type ExampleClass.
        GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
        list3.Add(new ExampleClass());
    }
29. 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, total number of objects in the pool. This reduces the overhead of creating and re-creating objects.
Object Pooling Vs Connection Pooling
"Object pooling lets you control the number of connections you use, as opposed to connection pooling, where you control the maximum number reached."
In case of object pooling, you can control the number of connections. In this case the pool will decide whether the maximum is reached or not for creation of objects. If it reached to the maximum level then the next available object will returned back. The drawback is, it increases the time complexity for heavy objects. In case of connection pooling, you can control the maximum number of connections reached. When you are using this pool, since there is nothing in the pool, still it will create connection on the same thread.
30. List down the commonly used types of exceptions in .Net?
ArgumentException, ArgumentNullException , ArgumentOutOfRangeException, ArithmeticException, DivideByZeroException ,OverflowException , IndexOutOfRangeException ,InvalidCastException ,InvalidOperationException , IOEndOfStreamException , NullReferenceException , OutOfMemoryException , StackOverflowException etc.
31. What are Custom Exceptions?
Sometimes there are some errors that need to be handeled as per user requirements. Custom exceptions are used for them and are used defined exceptions.
For  Implementing Custom Exception Handling, we need to derive the class CustomException from the system Base Class ApplicationException.
Any Custom Exception you create needs to derive from the System.Exception class. You can either derive directly from it or use an intermediate exception like SystemException or ApplicationException as base class.
Steps to Create Custom Exception
  1. Implement error handling in the user interface.
  2. Create and implement custom error messages.
  3. Create and implement custom error handlers.
  4. Raise and handle errors.
5.     try
   {
        
if (div == 0)
        {
            
throw new MyException();
         }
    }
    
catch (MyException e)
    {
         e.MyDivideException();
    }
         res = d / div;
         
Console.WriteLine("Result:{0}", res);
    }
6.    Here in the try block statements it might throw an exception whereas catch block handles that caused by the try block if one exists.

32. What are delegates?
Delegates are same are function pointers in C++ but the only difference is that they are type safe unlike function pointers. Delegates are required because they can be used to write much more generic type safe functions.
Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegateclass.
using System;
 
delegate int NumberChanger(int n);
namespace DelegateAppl {
   
   class TestDelegate {
      static int num = 10;
      
      public static int AddNum(int p) {
         num += p;
         return num;
      }
      public static int MultNum(int q) {
         num *= q;
         return num;
      }
      public static int getNum() {
         return num;
      }
      static void Main(string[] args) {
         //create delegate instances
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
         
         //calling the methods using the delegate objects
         nc1(25);
         Console.WriteLine("Value of Num: {0}", getNum());
         nc2(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}

33. How do you inherit a class into other class in C#?
Colon is used as inheritance operator in C#. Just place a colon and then the class name.
1
public class DerivedClass : BaseClass
 E.g.
1
System.Object
35. What is the difference between method overriding and method overloading?
In method overriding, we change the method definition in the derived class that changes the method behavior. Method overloading is creating a method with the same name within the same class having different signatures.
Method overloading happens in the same class shares the same method name but each method should have different number of parameters or parameters having different types and order. But in method overriding derived class have the same method with same name and exactly the same number and type of parameters and same return type as a parent class.
Method Overloading happens at compile time while Overriding happens at runtime. In method overloading, method call to its definition has happens at compile time while in method overriding, method call to its definition happens at runtime. 

36. What are the different ways a method can be overloaded?
Methods can be overloaded using different data types for parameter, different order of parameters, and different number of parameters.
37. Why can’t you specify the accessibility modifier for methods inside the interface?
In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in the derived class. That’s why they all are public.
38. How can we set class to be inherited, but prevent the method from being over-ridden?
Declare the class as public and make the method sealed to prevent it from being overridden.
39. What happens if the inherited interfaces have conflicting method names?
Implement is up to you as the method is inside your own class. There might be problem when the methods from different interfaces expect different data, but as far as compiler cares you’re okay.
40. What is the difference between a Struct and a Class?
Structs are value-type variables and classes are reference types. Structs stored on the stack, causes additional overhead but faster retrieval. Structs cannot be inherited.
1)The structures are value types and the classes are reference types.So object of structure store in stack exactly like any other value type like an Integer, a double but object of class store in heap.Your can assigned null to class variable but you can't assigned null value to structure variable
2)Class support Inheritance but struct does not support so access modifier of a member of a struct cannot be protected or protected internal
3)You can use Destructor in a class but You can use it in a structure
4)When passing a class to a method, it is passed by reference. When passing a struct to a method, it's passed by value instead of as a reference.
5)Structs cannot contain explicit parameterless constructors but You can create in class

41. How to use nullable types in .Net?
Value types can take either their normal values or a null value. Such types are called nullable types.

1
2
3
4
Int? someID = null;
If(someID.HasVAlue)
{
}

42. How we can create an array with non-default values?
We can create an array with non-default values using Enumerable.Repeat.
43. What is difference between is and as operators in c#?
“is” operator is used to check the compatibility of an object with a given type and it returns the result as Boolean.
“as” operator is used for casting of object to a type or a class.
44. What’s a multicast delegate?
A delegate having multiple handlers assigned to it is called multicast delegate. Each handler is assigned to a method.
Multicast delegate is an extension of normal delegate. It helps you to point more than one method at a single moment of time.
public partial class Form1 : Form
{
//1.decalre delegate
public delegate void MyDelegate();
private void Method1()
{
MessageBox.Show("Method1 Invoked");
}
//lock code start
private void Method2()
{
MessageBox.Show("Method2 Invoked");
}
//lock code End
private void button1_Click(object sender, EventArgs e)
{
//2.create delegate referance
MyDelegate myptr = null;
//3.point the referance to Add function
myptr += this.Method1;
////lock code start
myptr += this.Method2;
////lock code end
//4.invoke the method through delegate object
myptr.Invoke();
}
public Form1()
{
InitializeComponent();
}
}

Problems Associated with Multicast Delegates

1.     Subscriber has no authority to decide whether he interested in any event or not.
2.     If we change the program to provide authority to subscriber whether he is interested in event or not, then subscriber has got too much control. This means at that time subscriber can go and call any kind of method, he can make the delegate null.


 45. What are indexers in C# .NET?
Indexers are known as smart arrays in C#. It allows the instances of a class to be indexed in the same way as array.
E.g.
1
public int this[int index]    // Indexer declaration

46. What is difference between the “throw” and “throw ex” in .NET?
“Throw” statement preserves original error stack whereas “throw ex” have the stack trace from their throw point. It is always advised to use “throw” because it provides more accurate error information.
47. What are C# attributes and its significance?
C# provides developers a way to define declarative tags on certain entities eg. Class, method etc. are called attributes. The attribute’s information can be retrieved at runtime using Reflection.
48. How to implement singleton design pattern in C#?
In singleton pattern, a class can only have one instance and provides access point to it globally.
E.g.
1
2
3
4
Public sealed class Singleton
{
Private static readonly Singleton _instance = new Singleton();
}

49. What is the difference between directcast and ctype?
DirectCast is used to convert the type of an object that requires the run-time type to be the same as the specified type in DirectCast.
Ctype is used for conversion where the conversion is defined between the expression and the type.
50. Is C# code is managed or unmanaged code?
C# is managed code because Common language runtime can compile C# code to Intermediate language.

51. What is Event?
Event is a higher level of encapsulation over delegates. When we declare an event, then the client/Subscriber can only listen to the Event, He can’t do more than that.

Implementation of Event is a 3 step process.

1.     Declare - public delegate void CallEveryOne()
2.     Create - public Event CallEveryOne objEventCallEveryOne;
3.     Call- objEventCallEveryOne;

Difference between Delegates and Events

When we create an Event, the client can only listen to the Event, where when we create a delegate, the client will get lot of control over application (He can add/remove methods in delegate.).
public partial class Form1 : Form
{
public delegate void CallEveryOne();
//public CallEveryOne ptr;
public event CallEveryOne ptr;
Form2 obj;
Form3 obj2;
public Form1()
{
InitializeComponent();
}
private void Form1_Load_1(object sender, EventArgs e)
{
obj = new Form2(this);
obj2 = new Form3(this);
obj.Show();
obj2.Show();
}
private void button1_Click_1(object sender, EventArgs e)
{
//ptr.Invoke();
ptr();
}
}