Category Archives: C#

What are events in C#?

Events

  • Events is a way for a class to provide notifications to clients of that class when some interesting things happens to an object.
  • Events are declared using delegates.
  • Events can only be invoked from within the class that declared them.
  • Derived classes can not directly invoke events declared within the base class.
  • To call events in derived class, create a virtual protected invoking method for the event and override it in derived class.
  • An event can be placed in a interface.
  • When implementing the interface, the implementing class must supply a corresponding event in the class.

When to use var instead of type in C#.

Example 1

var i=10;
int i=10;


Here it is an optional to declare i as var type. Because we know the value is integer type.

Example 2

string[] fruits = { "mango", "apple", "grape", "banana" };
foreach (var s in fruits)
{
Console.WriteLine(s);
}
//OR
foreach (string s in fruits)
{
Console.WriteLine(s);
}


it is also an optional to use var instead of string. Because we know all elements are string.

Example 3
Use var when we have to deal with anonymous type data.

var anonArray = new[] { new { FirstName = "Dev", Age = 24 }, new { FirstName = "Vikas", Age = 21 } };

foreach (var arr in anonArray)
{
    Console.Write(arr.FirstName);
    Console.WriteLine(arr.Age);
}
Console.ReadKey();

Difference between Abstraction and Encapsulation.

Abstraction

  • Abstraction means hiding implementation.
  • Abstraction can be achieved by interfaces or abstract classes.
  • Abstraction focuses on the outside view of an object (i.e. the interface)
  • TV Remote is the real world example of abstraction where we know little bit how to operate it. but does not know how they are implemented internally.

Encapsulation

  • Encapsulation means hiding the important features of a class which is not been needed to be exposed outside of a class and exposing only necessary things of a class.
  • Encapsulation can be achieved by Access modifiers (Public, Private, Protected).
  • Encapsulation focuses on the inside view of an object where it is actually implemented(i.e the class).
  • TV contains multiple things inside it – Color tube, connections of Speaker, Channel mechanism. is the real time example of encapsulation where these things does not need to be exposed outside.

Why multiple inheritance of classes is not supported in C#?

Multiple inheritance of classes is not supported in C# because of the diamond problem.
Diamond Problem: If in a scenario there is a Class A have a Print method. And another classes B and C is overriding Class A Print method with single inheritance concept. Now we have a class D which inherit both these classes B and C with multiple inheritance concept.

Diamond Problem

Diamond Problem

Example :

class A
{
    public virtual void Print()
    {
        Console.Write("Print A");
    }
}

class B : A
{
    public override void Print()
    {
        Console.Write("Print B");
    }
}

class C : A
{
    public override void Print()
    {
        Console.Write("Print C");
    }
}

class D : B, C
{        
}


Now when we will create the object of Class D and call the Print method. Compiler will be confused which parent class method to call. Hence multiple inheritance of classes is not supported in C#.

Difference between Convert.ToString() and .ToString() method in C#.

Convert.ToString() method can handle null value and will not throw exception.
Example:

string FirstName = null; 
Console.Write(Convert.ToString(FirstName));


.ToString() method will throw exception (Object reference not set to an instance of an object.) while converting null value to string.

Example:

string FirstName = null;          
Console.Write(FirstName.ToString());
Console.ReadKey();


Exception : Object reference not set to an instance of an object.

Passing value to base class constructor c#.

“base” keyword is used to call and pass the value to the base class parameterised constructor in c#.
Base class constructor is called before the child class constructor.

class Numbers
{
    public Numbers(int a)
    {
        //code here
    }
}

class Addition : Numbers
{
    public Addition(int x)
        : base(x)
    {

    }
}

When to use interface and abstract class in C#.

  • Abstract classes have some implemented functionality so you can use the same functionality among all your implementations. Its the best example of re-usability of code. While Interfaces don’t provide any implementation of code.
  • If you are thinking about multiple version of your component then create abstract class. Abstract classes provide a simple and easy way to version your component. By updating base class, all the inheriting classes are automatically updated. While Interfaces can not be changed once created. Interfaces needs to be recreated.
  • Abstract classes are useful for large scale functionality While interface are useful in Small scale of functionality.

What is difference between overloading and overriding in C#?

Difference between overloading and overriding.

Overloading :

  • It means methods are declared with same name but different parameters (signatures).
  • It is also called compile time and early binding.
  • Example :-

    public class Overloading
      {
        public int CalculateAmt(int a, int b)  //Method with two int type Parameters.
        {
            return a + b;
        }
    
        public int CalculateAmt(int a, int b, int c)  //Same method name with different parameters.
        {
            return a * b * c;
        }
      }
    

Overriding :

  • It means methods are declared with same name and same parameters (signatures).
  • it is also called run time and late binding.
  • Method overriding is only possible in derived class.
  • Method overriding is not possible in the same class.
  • Only virtual and abstract methods in the base class can be overrides in derived class.
  • Example :

    //Base Class
    public class Math
      {
        public virtual int CalculateAmt(int a, int b)
        {
            return a + b;
        }
      }
    
    //Derived Class
    public class Calculator:Math
    {
        public override int CalculateAmt(int a, int b)
        {
           return a * b;
        }
    }
    

What is Static Constructor ?

A static constructor is used to initialize any static members, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
Example

class Date
{
    // Static variable that must be initialized at run time. 
    static readonly long currentDate;

    // Static constructor is called at most one time, before any 
    // instance constructor is invoked or member is accessed. 
    static Date()
    {
        currentDate= DateTime.Now;
    }
}

Note :

  • A static constructor does not take access modifiers or any parameters.
  • A static constructor can not be called directly.
  • The user has no control on static members when the static constructor is executed in the program.

What is Private Constructor ?

A private constructor is used in classes that contain static members only. Other classes (except nested classes) can not create instances of this private class.
Example

public class Counter
{
    private Counter() { }
    public static int iCount;
    public static int IncrementCount()
    {
        return ++iCount;
    }
}

class TestCounter
{
    static void Main()
    {
        // If you uncomment the following statement, it will generate 
        // an error because the constructor is inaccessible: 
        // Counter aCounter = new Counter();   // Error

        Counter.iCount= 100;
        Counter.IncrementCount();
        Console.WriteLine("New count: {0}", Counter.iCount);
    }
}
// Output: New count: 101