Base and Virtual Keyword in C#


The Base keyword is used to refer to the base class when chaining constructors or when you want to access a member (method, property, anything) of base class that has been overridden or hidden in the current class i.e in Derived Class. For example,

Virtual Keyword: This keyword can be used to the method, if we have to override that method in the derived class.

using System;
namespace BaseKeyword_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            Class2 obj = new Class2();
            obj.MyTest();//Output: I am from base class virtual method
            obj.Test();   //Output: I am from class 2 ovveride Method
            Console.ReadLine();
        }
    }
   public class Class1
    {
       public virtual void Test()
       {
           Console.WriteLine("I am from base class virtual method");
       }
    }
   class Class2:Class1
   {
       public override void Test()
       {
           Console.WriteLine("I am from class 2 override Method");
       }
       public  void MyTest()
       {
           base.Test(); // here we are calling base class method.                          
       }
   }
}

Summary:

We saw that base keyword is used to call the base class method in derived class. Only if that method had been overridden in class.

Virtual keyword can be used if we have to override that method in derived class.

What is the exact use of Delegate in C#?


This is the one of the frequently asked question in interview.Generally in interview, we will tell that “Delegate is the function pointer”. But this is not the exact answer of Delegate.

In the simple word “Delegate is the representative who helps us to make data communication between two parties”.

So in C# also Delegate is the process of doing data communication between two parties and main use of delegate is the callback.

Now let see the example, how delegate is making callback communication between two parties.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DelegateTest
{
class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
obj.LongRunningMethod(CallBack);

}
static void CallBack(int i)
{
Console.WriteLine(i);
}
}
class MyClass
{
public delegate void CallBack(int i);
public void LongRunningMethod(CallBack obj)
{
for (int i = 0; i < 10000; i++)
{
obj(i);
}
}
}
}

Delegate

Now in the above program, There are two class I.e. Program and MyClass . In myclass we have created one LongRunningMethod which is used for looping the number and we have created one delegate i.e Callback

In Program class, there is static Callback Method and Main Method. Now my requirement is there to whenever loop will execute then callback should happen and data should pass to Program class. Then I can use representative i.e. Delegate which will do my callback task.

For that I have created static Callback Method in Program Class and Callback delegate in MyClass and I am passing the object of Callback in LongRunningMethod as in above example.
In program class I am creating the object of MyClass then I am accessing the longRunningMethod and I am passing Callback method as Parameter.

So in this ways we are making the data communication between one class to other class using delegate.

Summary:
In the above example we saw that “Delegate in the representative which helps us to make data communication between two parties”.

What is the difference between Is and as Keyword in C# ?


Hi

One time i got this question in interview. Answer of this question , i have implemented in this code like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//The is operator is used to check whether the run-time type of an object is compatible with a given

object num=10;
if (num is int)
{
Response.Write(“Num is integer”);
}

//The as operator is used to perform conversions between compatible types.

object ss = “This sis the string”;
string str = string.Empty;
if (ss is string)
{
str = ss as string;

Response.Write(str);
}

}
}

Dictionary in C#


Dictionary is used to represent a collection of key and Value pair of data. It is a generic class and it can store any data type. It came with .net F/W 2.0.

Dictionary contains key and value together as shown in given example below


 protected void Page_Load(object sender, EventArgs e)
    {
        Dictionary<string, int> Emps = new Dictionary<string, int>();
        Emps.Add("Ram", 1);
        Emps.Add("Mohan", 2);
        Emps.Add("Hari", 3);
        foreach (var name in Emps)
        {
            lblmsg.Text += name.Key + " " + name.Value  +"<br>";
        }     
    }

Then output will come like this

Ram 1
Mohan 2
Hari 3

ContainKey and ContainValue Method

It has containkey and ContainValue method. Using ContainKey we can find the specific key in dictionary and using ContainValue we can get the specific value. It returns the Boolean value.


 if(Emps.ContainsKey("Hari"))
        {
            int value = Emps["Hari"];
            lblmsg.Text = value.ToString();
        }


It has also add,remove and Clear method.

Advantages

1. Dictionary type provides fast lookups with keys to get values.
2. It stores any datatype
3. It provide good performance as compare to HashTable

What is the abstract class ?


Hi
This is one of the frequently asked questions in interview. I have faced this question in almost in all interviews. So let’s understand what is abstract class?

Abstract class is the class which one cannot be instantiated. This means we canot create object of this class like general class. To use it, we need to inherit it. It contains the abstract keyword.

In abstract class, we can define
1. Normal Property
2. Abstract Property
3. Normal Method
4. Abstract Method
5. Virtual method.

Now let see this concept with example


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Class1
/// </summary>
public abstract class Class1
{
    public virtual string SayHello()
    {
        return "Hello from virual method";
    }

    public string sayHello2()
    {
        return "I m from SayHello Method";
    }

    public abstract string SayHello1();

}

Note: Here i have created the abstract class which contain Normal method,abstract method and Virtual method.

Now we will inherit this class in class2 like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Class2
/// </summary>
public class Class2:Class1
{
    public override string SayHello()
    {
        return "This is the orveride message using virtual method";
    }

    public override string SayHello1()
    {
        return "This is the orveride message using abstract message";
    }


}

Note: in the above code i have override the virtual and abstract method. So if virtual or abstract keyword is there then we have to must override it.

Now we will call this method in default.cs page like this on button click event


 protected void Button1_Click(object sender, EventArgs e)
    {
         Class2 obj = new Class2();
       
        Response.Write(obj.SayHello()+"<br>"); 
        Response.Write(obj.SayHello1()); 
        
    }

Now compile the code, we will get output like this

override

When to use abstract Class?

We can use this class in this senario

1. If we have created some class and we want to modify some methods with new feature and we have to use somewhere then we can use abstract class

2. If we are developing some product type project, where we have to keep on adding new features in coming days then we can use abstract class.

Note: This is all my understanding my abstract class, if you feel i missing some important point then let me know. You are always welcome.