C#

1. What is latest version of C# with features?


2. Const vs ReadOnly vs Static

Constant
Constant fields are defined at the time of declaration in the code snippet, because once they are defined they can't be modified. By default a constant is static, so you can't define them static from your side.
It is also mandatory to assign a value to them at the time of declaration otherwise it will give an error during compilation of the program snippet. That's why it is also called a compile-time constant.

ReadOnly
A Readonly field can be initialized either at the time of declaration or within the constructor of the same class. We can also change the value of a Readonly at runtime or assign a value to it at runtime (but in a non-static constructor only).
For that reason a Readonly field is also called a run-time constant.

Static
A static member (variable, method, etc) belongs to the type of an object rather than to an instance of that type.

For more modifiers (in, out, override, sealed, static, unsafe, virtual, volatile) please visit https://msdn.microsoft.com/en-us/library/acdd6hb7.aspx

3. Ref vs Out

Ref - The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the called method is reflected in the calling method.
For more https://msdn.microsoft.com/en-us/library/14akc2c7.aspx

Out - The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword. For more https://msdn.microsoft.com/en-us/library/t3c3bfhx.aspx

4. What is Inheritance? Why C# does not support multiple Inheritance.
Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class.
For more https://msdn.microsoft.com/en-us/library/ms173149.aspx
C# does not support multiple Inheritance
To understand this you need to understand the Diamond problem first:
Image result for diamond problem


The Diamond problem (sometimes referred to as the "deadly diamond of death") is an ambiguity that arises when two classes B and C inherit from Class A and class D inherits from both B and C.
 If a method in D calls a method defined in A(and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B or C?

That is the reason why C# does not support multiple inheritance.

5. What is Abstraction and Encapsulation? How it is different from each other?

Abstraction-
Abstraction is the process of refining away all the unneeded/unimportant attributes of an object and keep only the characteristics best suitable for your domain.
Abstraction allows making relevant information visible.
Example - A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, USB ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker’s works.  You just need to know how to operate the laptop by switching it on.
Note- When derived class inherited with abstract class; derived class must be override abstract class methods.

Encapsulation- 
Encapsulation is the first pace. Encapsulation is the procedure of covering up of data and functions into a single unit (called class).
The need of encapsulation is to protect or prevent the code (data) from accidental corruption due to the silly little errors that we are all prone to make. In Object oriented programming data is treated as a critical element in the program development and data is packed closely to the functions that operate on it and protects it from accidental modification from outside functions.
we can 
1. ENCAPSULATION USING ACCESSORS AND MUTATORS
2. ENCAPSULATION USING PROPERTIES
For More http://www.c-sharpcorner.com/article/encapsulation-in-C-Sharp/

6. What is Polymorphism? Describe what is static and Dynamic Polymorphism?

In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'. 
Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.
C# provides two techniques to implement static polymorphism. They are:
1.Function overloading
2.Operator overloading
For more https://www.tutorialspoint.com/csharp/csharp_polymorphism.htm

Dynamic polymorphism is implemented by abstract classes and virtual functionsFor more https://msdn.microsoft.com/en-us/library/ms173152.aspx

7. What is Shadowing or Hiding?

Shadowing is a VB.NET concept. In C#Shadowing is known as Hiding. It hides the base class method. It is accomplished using the 'new' keyword. Override keyword is used to provide a completely new implementation of a base class method (which is marked 'Virtual') in the derived class.
If the derived class is not happy, one of the functions available to it from the base class can define its own version of the same function with the same function signature, just differing in implementation. This new definition hides the base class definition.
class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class Demo
{
  public static void Main()
  {
     DC obj = new DC();
     obj.Display();
  }
}
Output : DC:Display
On compilation the above program threw a warning which said
P2.cs(11,15): warning CS0108: 'DC.Display()' hides inherited member 
'BC.Display()'. Use the new keyword if hiding was intended. P2.cs(3,15): 
(Location of symbol related to previous warning)
So modify the code as below.
class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}
so 'new' keyword is used for Method Hiding.

8. What is the deference between Interface and Abstract class? What is the need of these?

Abstract class - The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.
An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
public abstract class A
{
    public abstract void DoWork(int i);
}
public class B:A
{
    public void DoWork(int i){//implementation }
}
Interface - An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition. Interface is contract for clients.
interface ISampleInterface
    {
        void SampleMethod();
    }
An interface can be a member of a namespace or a class and can contain signatures of the following members:

Interface vs abstract class

InterfaceAbstract class
Interface support multiple inheritanceAbstract class does not support multiple inheritance
Interface does'n Contains Data MemberAbstract class contains Data Member
Interface does'n contains CunstructorsAbstract class contains Cunstructors
An interface Contains only incomplete member (signature of member)An abstract class Contains both incomplete (abstract) and complete member
An interface cannot have access modifiers by default everything is assumed as publicAn abstract class can contain access modifiers for the subs, functions, properties
Member of interface can not be StaticOnly Complete Member of abstract class can be Static
Need Of Interface - As it support multiple Inheritance , Class does not. Most of the Design Patterns and Principles are based on interfaces rather than class inheritance. Some of the examples are Factory Pattern, Interface Segregation Principle and so on.
Interface is used in WCF to define service contracts.

For more  Abstract Class  Interface

9. Can Virtual or Abstract member be declare private ?

  No - it will show compile time error.
virtual void display()
        {
        // Implementation

        }

10. What will be output of below program? Line 38 will throw any error?


  class A
    {
       public virtual void display()
        {
            Console.WriteLine("A - display");
        }
    }

    class B:A
    {
        public override void display()
        {
            Console.WriteLine("B - display");
        }
    }

    class Test
    {
        static void Main()
        {
            A obj = new A();
            obj.display();

            A obj1 = new B();
            obj1.display();

            B o = new B();
            o.display();

            // B ob = new A(); Line 38
            Console.ReadLine();

        }

    }
Output: Line 38 will throw error - Cannot implicitly convert type 'A' to 'B'. An explicit conversion exists (are you missing a cast?). And o/p as below.

A - display
B - display
B - display

11. Can Abstract class has constructor? Below code will compile or not.or it will give any error in Error line 1 or 2.

Yes, Abstract class can has constructor.

    class A
    {
       public virtual void display()
        {
            Console.WriteLine("A - display");
        }
        public virtual void disp()
        {
            Console.WriteLine("A - disp");
        }
    }
abstract class ab :A
    {
        public ab()
        {

        }
        public abstract override void display(); Error line 1

        public sealed override void disp()  Error Line 2
        {
            Console.WriteLine("disp is sealed now.");
        }
    }

It will compile successfully. and we can add abstract or sealed keyword with override keyword.

12. What is the difference between Var, Object and Dynamic?
From below example we will find difference.
class Program
    {
        static void Main(string[] args)
        {
            var x = 10;
            object y = 20;
            dynamic z = 30;

            x = "bhanu"; // Error -  Cannot implicitly convert type 'string' to 'int'

            y = "bhanu";
            y = y - 10;  //Error Operator '-' cannot be applied to operands of type 'object' and 'int'

                   z = "bhanu";
            z = z - 10;
            Console.WriteLine("{0},{1},{2}",x,y,z);
            Console.ReadLine();
        }

        void disp(var x) // Error CS0825  The contextual keyword 'var' may only appear within a local variable declaration or in script code
        {

        }
        void disp(object x)
        {

        }
        void disp1(dynamic x)
        {

        }

    }
Object
Var
Dynamic
Object was introduced with C# 1.0
Var was introduced with C# 3.0
Dynamic was introduced with C# 4.0
It can store any kind of value, because object is the base class of all type in .NET framework.
It can store any type of value but It is mandatory to initialize var types at the time of declaration.
It can store any type of the variable, similar to old VB language variable.
Compiler has little information about the type.
It is type safe i.e. Compiler has all information about the stored value, so that it doesn't cause any issue at run-time.
It is not type safe i.e. Compiler doesn't have any information about the type of variable.
Object type can be passed as method argument and method also can return object type. as in above example.
Var type cannot be passed as method argument and method cannot return object type. Var type work in the scope where it defined.refer example
Dynamic type can be passed as method argument and method also can return dynamic type.
refer example
Need to cast object variable to original type to use it and performing desired operations.
No need to cast because compiler has all information to perform operations.
Casting is not required but you need to know the properties and methods related to stored type.
Cause the problem at run time if the stored value is not getting converted to underlying data type.
Doesn't cause problem because compiler has all information about stored value.
Cause problem if the wrong properties or methods are accessed because all the information about stored value is get resolve only at run time.
Useful when we don’t have more information about the data type. refer example
Useful when we don’t know actual type i.e. type is anonymous. refer example
Useful when we need to code using reflection or dynamic languages or with the COM objects, because you need to write less code.

For more click Var  Object  Dynamic

13. What is Boxing and Unboxing ?
Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. 

In the following example, the integer variable i is boxed and assigned to object o.
int i = 123;
            // The following line boxes i.
            object o = i; 
The object o can then be unboxed and assigned to integer variable i:
o = 123;
            i = (int)o;  // unboxing
For More Boxing and Unboxing
14. What is Method Overloading?

Use same method name with Different Signature.Signature does not include return type.
For method overloading you can use different types of parameter or different sequence of parameter or different number of parameter. 
Example - 
        void display(int x)
        {
        // Implementation
        }
        void display(float x)
        {
            // Implementation
        }
        void display(int x, int y)
        {
            // Implementation

        }

15. What is use of Sealed Class and class members?

A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.
When applied to a class, the sealed modifier prevents other classes from inheriting from it.
Example - 
  public sealed class D
    {
        // Class members here.
    }
You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.
public class C
{
    public virtual void DoWork() { }
}
public class D : C
{
    public sealed override void DoWork() { }
}
For more Sealed Class

16. What is Interpolated String?
An interpolated string expression looks like a template string that contains expressions. An interpolated string expression creates a string by replacing the contained expressions with the ToString represenations of the expressions’ results. An interpolated string is easier to understand with respect to arguments than Composite Formatting. Here is an example of an interpolated string.


string name = "Bhanu";
Console.WriteLine($"Name = {name}")
Output - Name = Bhanu
Example 2 -
class Program
{
    static void Main()
    {
 int id = 100;
 // We can use an expression with a string interpolation.
 string result = $"The multiplied ID is {id * 10}";
 Console.WriteLine(result);
    }
}

Output

The multiplied ID is 1000
For More Interpolated String MSDN String-Interpolation

17. What is Difference between Abstract and Virtual
When an instance method declaration includes an abstract modifier, that method is said to be an abstract method. Although an abstract method is implicitly also a virtual method, it cannot have the modifier virtual.
An abstract method declaration introduces a new virtual method but does not provide an implementation of that method. Instead, non-abstract derived classes are required to provide their own implementation by overriding that method. Because an abstract method provides no actual implementation, the method-body of an abstract method simply consists of a semicolon.
// compile with: /target:library
    public class D
    {
        public virtual void DoWork(int i)
        {
            // Original implementation.
        }
    }
    public abstract class E : D
    {
        public abstract override void DoWork(int i);
    }
 
    public class F : E
    {
        public override void DoWork(int i)
        {
            // New implementation.
        }
    }
The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it:
   public class Shape
        {
            public const double PI = Math.PI;
            protected double x, y;
            public Shape()
            {
            }
            public Shape(double x, double y)
            {
                this.x = x;
                this.y = y;
            }

            public virtual double Area()
            {
                return x * y;
            }
        }
public class Circle : Shape
        {
            public Circle(double r) : base(r, 0)
            {
            }

            public override double Area()
            {
                return PI * x * x;
            }
        }
For Virtual method it is optional to provide Implementation in derived class.
When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.

18. What is covariant and contravariant?
Covariance and contravariance are terms that refer to the ability to use a less derived (less specific) or more derived type (more specific) than originally specified. Generic type parameters support covariance and contravariance to provide greater flexibility in assigning and using generic types. When you are referring to a type system, covariance, contravariance, and invariance have the following definitions. The examples assume a base class named Baseand a derived class named Derived.
  • Covariance
    Enables you to use a more derived type than originally specified.
    You can assign an instance of IEnumerable<Derived> (IEnumerable(Of Derived) in Visual Basic) to a variable of type IEnumerable<Base>.
  • IEnumerable<string> strings = new List<string>();
    IEnumerable<object> objects = strings; 
  • Contravariance
    Enables you to use a more generic (less derived) type than originally specified.
    You can assign an instance of IEnumerable<Base> (IEnumerable(Of Base) in Visual Basic) to a variable of type IEnumerable<Derived>.
  • Action<object> actObject = SetObject;  
    Action<string> actString = actObject; 
  • Invariance
    Means that you can use only the type originally specified; so an invariant generic type parameter is neither covariant nor contravariant.
    You cannot assign an instance of IEnumerable<Base> (IEnumerable(Of Base) in Visual Basic) to a variable of type IEnumerable<Derived>or vice versa.
  • For more 1.Covariance and Contravariance  2. Covariance and Contravariance
19. What is Output of following Program? or any Error?
public void display()
        {
            int x = 0;
            int y = 10;
            try
            {
                int z = y / x;
            }
            catch (Exception)
            {
                throw;
            }
            catch (DivideByZeroException)
            {
                throw;
            }
            finally
            {
            }
        }
Output - It will generate compile time error.
A previous catch clause already catches all exceptions of this or of a super type ('Exception').

So Order of Catch Block is important as below.
First Any specific type of exception.
In last give General Exception.

20. Important points about try, catch and finally.
        public int display()
        {
            int x = 0;
            int y = 10;
            try
            {
                int z = y / x;
                return 0;
            }

            catch (DivideByZeroException)
            {
                Console.WriteLine("DivideByZeroException");
                //throw;
                return 1;
            }
            catch (Exception)
            {
                Console.WriteLine("general exception");
                //throw;
                return 2;
            }
            finally
            {
                Console.WriteLine("finally");
            }
        }

1. If method is returning some thing then return from try and all catch blocks.
2. Finally block never accepts return or throw (without argument) keywords.
3. Always put catch blocks in Order as described in question 19.
4. In finally you can give like throw new Exception("ex");
5. If a method return something then instead of returning from every try catch block
you can throw from Finally block only as in below example.
6. You can use only try and finally block. Catch block is not necessary.
public int display()
        {
            int x = 0;
            int y = 10;
            try
            {
                int z = y / x;
                //return 0;
            }

            catch (DivideByZeroException)
            {
                Console.WriteLine("DivideByZeroException");
                //throw;
                //return 1;
            }
            catch (Exception)
            {
                Console.WriteLine("general exception");
                //throw;
                //return 2;
            }
            finally
            {
                Console.WriteLine("finally");
                throw new Exception("bhanu");
            }

        }

21. What are Non-Generic Collection and Generic Collection? What are benefits of Generic collections?
Non-Generic Collection -  When you want to create and manage groups of related objects. There are two ways to group objects: by creating arrays of objects, and by creating collections of objects.
The .NET Framework provides specialized classes for data storage and retrieval. These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces, and these interfaces may be inherited to create new collection classes that fit more specialized data storage needs.
The following table lists some of the frequently used classes in the System.Collections namespace:
Example
ArrayList li = new ArrayList();
ClassDescription
ArrayListRepresents an array of objects whose size is dynamically increased as required.
HashtableRepresents a collection of key/value pairs that are organized based on the hash code of the key.
QueueRepresents a first in, first out (FIFO) collection of objects.
StackRepresents a last in, first out (LIFO) collection of objects.
Generic Collection - The System.Collections.Generic namespace contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.
The following table lists some of the frequently used classes of the System.Collections.Generic namespace:
Example -
List<int> list = new List<int>();
ClassDescription
Dictionary<TKey, TValue>Represents a collection of key/value pairs that are organized based on the key.
List<T>Represents a list of objects that can be accessed by index. Provides methods to search, sort, and modify lists.
Queue<T>Represents a first in, first out (FIFO) collection of objects.
SortedList<TKey, TValue>Represents a collection of key/value pairs that are sorted by key based on the associated IComparer<T>implementation.
Stack<T>Represents a last in, first out (LIFO) collection of objects.
For More Collection
Benefits of Generic Collection - 

1. Generic collection are type safe as these have type information at Compile time Where non-generic collection are not type safe.
2. Generic Collection has better performance as Boxing and Unboxing is not performed but in Non-generic collection Boxing and unboxing is performed.

22. What is IDisposable interface? Implementation of dispose method.

IDisposable interface Provides a mechanism for releasing unmanaged resources. 
The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.
Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.
IDisposable and the inheritance hierarchy

A base class with subclasses that should be disposable must implement IDisposable as follows. You should use this pattern whenever you implement IDisposable on any type that isn't sealed (NotInheritable in Visual Basic).

1. It should provide one public, non-virtual Dispose() method and a protected virtual Dispose(Boolean disposing) method.
2. The Dispose() method must call Dispose(true) and should suppress finalization for performance.
3. The base type should not include any finalizers.

dispose pattern - 
class BaseClass : IDisposable
{
   // Flag: Has Dispose already been called?
   bool disposed = false;

   // Public implementation of Dispose pattern callable by consumers.
   public void Dispose()
   {
      Dispose(true);
      GC.SuppressFinalize(this);           
   }

   // Protected implementation of Dispose pattern.
   protected virtual void Dispose(bool disposing)
   {
      if (disposed)
         return;

      if (disposing) {
         // Free any other managed objects here.
         //
      }

      // Free any unmanaged objects here.
      //
      disposed = true;
   }
 // If you override Finalize method
   ~BaseClass()
   {
      Dispose(false);
   }

}
For more in Detail IDisposable Interface    Dispose Method

23. What is Garbage Collector and Generations for it.
In the common language runtime (CLR), the garbage collector serves as an automatic memory manager. It provides the following benefits:
  • Enables you to develop your application without having to free memory.
  • Allocates objects on the managed heap efficiently.
  • Reclaims objects that are no longer being used, clears their memory, and keeps the memory available for future allocations. Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field.
  • Provides memory safety by making sure that an object cannot use the content of another object.
Generations-
The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage collection primarily occurs with the reclamation of short-lived objects that typically occupy only a small part of the heap. There are three generations of objects on the heap:

Generation 0. This is the youngest generation and contains short-lived objects. An example of a short-lived object is a temporary variable. Garbage collection occurs most frequently in this generation.
Newly allocated objects form a new generation of objects and are implicitly generation 0 collections, unless they are large objects, in which case they go on the large object heap in a generation 2 collection.
Most objects are reclaimed for garbage collection in generation 0 and do not survive to the next generation.
Generation 1. This generation contains short-lived objects and serves as a buffer between short-lived objects and long-lived objects.
Generation 2. This generation contains long-lived objects. An example of a long-lived object is an object in a server application that contains static data that is live for the duration of the process.

24. What Is using Statement ?

Provides a convenient syntax that ensures the correct use of IDisposable objects.
using (StreamReader sr = new StreamReader(filename))
            {
                txt = sr.ReadToEnd();
            }
The using statement calls the Disposemethod on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Disposeis called. Within the using block, the object is read-only and cannot be modified or reassigned.
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. 


try {

         sr = new StreamReader(filename);

         txt = sr.ReadToEnd();

      }

      finally {

         if (sr != null) sr.Dispose();     

      }

25. What is Finalizer and SupressFinalize method?

Requests that the common language runtime not call the finalizer for the specified object.
The IDisposable.Dispose method lets users release resources at any time before the object becoming available for garbage collection. If the IDisposable.Dispose method is called, it frees resources of the object. This makes finalization unnecessary. IDisposable.Dispose should call GC.SuppressFinalize so the garbage collector does not call the finalizer of the object.
For More GC.SupressFinalize

26. What will output of below Program?

            int a = 0;
            try
            {
                int x = 4;
                int y ;
                try
                {
                    y = x / a;
                }
                catch (Exception e)
                {
                    Console.WriteLine("inner ex");
                    //throw;   // Line 1
                    //throw e;   // Line 2
                    //throw new Exception("devide by 0");  // Line 3
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("outer ex");
                throw ex;
            }

1. if all Line 1 ,2 and 3 are commented -
Output - inner ex

2. if all Line 2 and 3 are commented -
Output - inner ex
              System.DevideByZeroException: {"Attempted to divide by zero."}---------

3. if all Line 1 and 2 are commented -
Output - inner ex
              System.Exception: devide by 0 ----

4. if all Line 1 and 3 are commented -

Output - inner ex
              System.DevideByZeroException: {"Attempted to divide by zero."}---------
and StackTrace will be reset in case of throw ex;

27. What is use of Object.Equals Method? and Differentiate '==' and equal method.

Equals method Determines whether the specified object is equal to the current object.
The type of comparison between the current instance and the objparameter depends on whether the current instance is a reference type or a value type.
If the current instance is a reference type, the Equals(Object) method tests for reference equality, and a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method. Reference equality means that the object variables that are compared refer to the same object. The following example illustrates the result of such a comparison.
Program p = new Program();
            Program p2 = p;
            Program p1 = new Program();

            if (p.Equals(p2))
            {
                Console.WriteLine("p and p2 are equal");
            }
            if (p1.Equals(p2))
            {
                Console.WriteLine("p1 and p2 are equal");
            }
            else
            {
                Console.WriteLine("p1 and p2 are not equal");
            }
Output p and p2 are equal
         p1 and p2 are not equal


If the current instance is a value type, the Equals(Object) method tests for value equality. Value equality means the following:

byte value1 = 12;
            int value2 = 12;
            object object1 = value1;
            object object2 = value2;
            Console.WriteLine("{0} ({1}) = {2} ({3}): {4}",
                    object1, object1.GetType().Name,
                    object2, object2.GetType().Name,
                    object1.Equals(object2));

Output - 12 (Byte) = 12 (Int32): False

Differences - Use the equals() method to see if two different objects are equal.Both the == Operator and the Equals() method are used to compare two value type data items or reference type data items.
The Equality Operator ( ==) is the comparison operator and the Equals() method compares the contents of a string. The == Operator compares the reference identity while the Equals() method compares only contents.

StringBuilder sb1 = new StringBuilder("Asp.Net");

StringBuilder sb2 = new StringBuilder("Asp.Net");

sb1 == sb2 returns false and sb1.Equals(sb2) returns true.

28. What are Value Type and Reference Type?

A data type is a value type if it holds the data within its own memory allocation. Value types include the following:
  • All numeric data types
  • BooleanChar, and Date
  • All structures, even if their members are reference types
  • Enumerations, since their underlying type is always SByteShortIntegerLongByteUShortUInteger, or ULong
  • For More Value Types

reference type contains a pointer to another memory location that holds the data. Reference types include the following: 
  • String
  • All arrays, even if their elements are value types
  • Class types, such as Form
  • Delegates     
  • For More Reference Types
A class is a reference type. For this reason, reference types such as Object and String are supported by .NET Framework classes. Note that every array is a reference type, even if its members are value types.

29. Other use of new keyword rather than creating new object?
 'new' keyword is used for Method Hiding for more refer question number 7 and for Anonymous Types.

30. What are the Extension methods?
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.
Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
The following example shows an extension method defined for the System.String class. Note that it is defined inside a non-nested, non-generic static class:
namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, 
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }   
}
The WordCount extension method can be brought into scope with this using directive. 
using ExtensionMethods; And it can be called from an application by using this syntax: string s = "Hello Extension Methods"; int i = s.WordCount(); For More Extension Methods
31. What are Partial Class and Methods?
The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace. All the parts must use the partialkeyword. All the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as publicprivate, and so on.
If any part is declared abstract, then the whole type is considered abstract. If any part is declared sealed, then the whole type is considered sealed. If any part declares a base type, then the whole type inherits that class.
public partial class Employee
    {
        public void DoWork()
        {
        }
    }
 
    public partial class Employee
    {
        public void GoToLunch()
        {
        }
    }
A partial class or struct may contain a partial method. One part of the class contains the signature of the method. An optional implementation may be defined in the same part or another part. If the implementation is not supplied, then the method and all calls to the method are removed at compile time.
Partial methods enable the implementer of one part of a class to define a method, similar to an event. The implementer of the other part of the class can decide whether to implement the method or not. If the method is not implemented, then the compiler removes the method signature and all calls to the method.
// Definition in file1.cs  
partial void onNameChanged();  
  
// Implementation in file2.cs  
partial void onNameChanged()  
{  
  // method body  
}  
For More Partial Keyword
32. What are Anonymous Types?
Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.
You create anonymous types by using the new operator together with an object initializer. 
var v = new { Amount = 108, Message = "Hello" };  
  
// Rest the mouse pointer over v.Amount and v.Message in the following  
// statement to verify that their inferred types are int and string.  
Console.WriteLine(v.Amount + v.Message);
For More Anonymous Types

33. In How many ways can you Pass Parameters in C#?
In C#, arguments can be passed to parameters either by value or by reference. Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment. To pass a parameter by reference, use the ref or out keyword. 
For more information, see the following topics:
34.What is the difference between an EXE and a DLL?

An exe is an executible program whereas A DLL is a file that can be loaded and executed by programs dynamically. An EXE is visible to the system as a regular Win32 executable. Its entry point refers to a small loader which initializes the .NET runtime and tells it to load and execute the assembly contained in the EXE.
A .dll file contains compiled code you can use in your application to perform specific program functions and may be required by another application or module (such as .exe or .dll) to load it through an entry point. It is a library that contains code and data that can be used by more than one program at the same time.

35. Class Library Project vs Web API.
If you use a class library it will be faster in terms of performance compared to Web API because there won't be any serialization or I/O involved when calling a method. The drawback of a class library is that your clients need to be .NET clients. As a consequence this is not an inter operable solution. Also if you decide to make changes to the implementation later you will have to update all clients with the new version of the class library whereas with the Web API you would do it in a single location -> your web server on which the Web API is hosted.

36. What is DLL hell Problem?
DLL Hell refers to the set of problems caused when multiple applications attempt to share a common component like a dynamic-link library (DLL) or a Component Object Model (COM) class. In the most typical case, one application will install a new version of the shared component that is not backward compatible with the version already on the machine. Although the application that has just been installed works fine, existing applications that depended on a previous version of the shared component might no longer work. 
The reason for these issues is that version information about the different components of an application aren't recorded or enforced by the system.  For More DLL Hell Problem and Solution

Solution to DLL Hell Problem - Versioning is the solution to this problem.
Each assembly has a four-part version number as part of its identity (that is, version 1.0.0.0 of some assembly and version 2.1.0.2 are completely different identities as far as the class loader is concerned).
The parts of the version number are major, minor, build and revision. 
To share the Assemblies by all Application we store in GAC.

The Global Assembly Cache (GAC)
is a folder in Windows directory to store the .NET assemblies that are specifically designated to be shared by all applications executed on a system. Assemblies can be shared among multiple applications on the machine by registering them in global Assembly cache(GAC). For More GAC.

37. What is Asynchronous Programming and how will you implement in C#?
please refer my post Asynchronous-programming

4 comments: