What is the use of this Keyword in C# ?


This keyword is used to refer the current instance of class. It is also used as modifier of the first parameter of an extension method.

The following are the common use of this Keyword
1. To qualify the member hidden by similar name.
2. To pass object as parameter to other methods

Let see one simple example for this

using System;

namespace This_Keyword_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create object
            Employee objEmp = new Employee("Chandradev","Prasad");
            //Display result
            objEmp.printEmployee();
            Console.ReadKey();
        }
    }
    class Tax
    {
       public static decimal CalcTax(Employee E)
        {
            return 0.08m * E.Salary;
        }
    }
    class Employee
    {
        private string firstName;
        private string lastName;
        private decimal salary = 5000m;
        public  Employee(string firstName,string lastName)
        {
            this.firstName = firstName;
            this.lastName = lastName;
        }   

        public void printEmployee()
        {
            Console.WriteLine("FirstName: {0}\nLastName: {1}",firstName,lastName);
            Console.WriteLine("Taxes: {0:C}",Tax.CalcTax(this));
        }
        public decimal Salary
        {
            get { return salary; }
        }

    }
}

This_Keyword
Explanation:

In the above example, this.name and this.alias is representing the private string value of Employee class
And in Tax.calcTax(this) , we are passing the class objet of Employee as parameter to other CalcTax method of Tax class.

Let see one more simple example of this Keyword

using System;

namespace This_Keyword
{
    class Program
    {
        static void Main(string[] args)
        {
            Test obj = new Test();
            obj.Get();
        }
    }
    class Test
    {
        int a=10,b=20;
        public void Get()
        {
            int a = 30, b = 40;
            Console.WriteLine("The class variable are a={0},b={0}", this.a, this.b);
            Console.WriteLine("The Local Variable are a={0},b={0}",a,b);
            Console.ReadLine();
        }

    }
}

This1
Explanation:

In the above example we are differentiating the class variable i.e. global variable and local variable when both the variable names are same. If we will use the this keyword then it will show only class variable i.e. Global variable.

There are several usages of this keyword in C#.

1. To qualify members hidden by similar name
2. To have an object pass itself as a parameter to other methods
3. To have an object return itself from a method
4. To declare indexers
5. To declare extension methods
6. To pass parameters between constructors
7. To internally reassign value type (struct) value.
8. To invoke an extension method on the current instance
9. To cast itself to another type
10. To chain constructors defined in the same class

Named and optional Parameter in C#


Named and optional parameters are the one of the new features of C# 4.0. This feature allows developers to have an option to create named and optional parameters in a method.

Named Parameter

Now let see the example of Named Parameter:

NamedParameter

Complete C# code

using System;

namespace Named_OptionalParameter
{
    class Program
    {
        static void Main(string[] args)
        {
            var objPrice = new PriceClass();
            //Traditional approach to Call the method
            Console.WriteLine(objPrice.CalculatePrice(10,100,false));
            // Using Named parameter approach to call the method
            Console.WriteLine(objPrice.CalculatePrice(EliteMember:false,quantity:10,price:100));
            Console.ReadLine();
        }
    }
    public class PriceClass
    {
        public double CalculatePrice(int quantity,double price, bool EliteMember)
        {
            if (EliteMember)
            {
                return quantity * price - 10;
            }
            else
                return quantity * price;
        }
    }
}

In the above code we saw that we have created the method to calculate price and we are passing the parameter as int, double, bool as parameter. But if we will not pass in this order it will through the exception upto C# 3.0. But from C# 4.0 there is not mandatory to pass parameter as same as method defined.

We can pass parameter as per as developer desire like this
// Using Named parameter approach to call the method

Console.WriteLine(objPrice.CalculatePrice(EliteMember:false,quantity:10,price:100));

Optional Parameter

Now let see the example of Optional parameter example

OptionalParameter

If you will see in the above example, CalculatePrice Method has two parameter i.e price and eliteMember. For that parameter it is not mandatory to pass the parameter. If we will not pass the parameter then it will take default value which one we have defined in parameter.

For example, if we have to override the optional value of method then this also possible, we have to just pass the desire value in parameter as shown in above image.

Summary:

We learned that what is the named and optional parameter in C#

Extension Method in C#


Extension method is the one of the cool features came in C# 3.0. As the name suggest, it extends the functionality of method in very simple way.

For example, we are going to use some dll method and we don’t have access to inherit or override the class. But our requirement is there to extend the method with some extra functionality. Then extension method will very handy to use in this scenario.

Let’s see one extremely simple example

Extension_Method

Complete code in C#

using System.Collections.Generic;
 
namespace ExtensionMethod
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            EmpElite objee = new EmpElite();
            objee.AllEliteEmps(); //This will contains Ram, Mohan,Hari
            objee.NewEliteEmps(); //This will contains John,James,Suresh
        }
    }
 
    public class EmpElite
    {
        public List<string> AllEliteEmps()
        {
            return new List<string> { "Ram", "Mohan", "Hari" };
        }
    }
 
    public static class ExtendedEmpElite
    {
        public static List<string> NewEliteEmps(this EmpElite elite)
        {
            return new List<string>() { "John", "James", "Suresh" };
        }
    }
}

Note:
In the above example, we saw that there is one EmpElite Class with AllEliteEmps method, Which contains the list of elite Emps. We have extended the AllEliteEmps method with NewEliteEmps using static Keyword and this Keyword. We have also passed the Class name and instance name which one we are going to extend.

Now whenever we will call this method i.e. ExtendedEmpElite then we will get the expected output.

Point to remember:
• An extension method must be defined in a top-level static class.
• An extension method with the same name and signature as an instance method will not be called.
• Extension methods cannot be used to override existing methods.
• The concept of extension methods cannot be applied to fields, properties or events.

What is the attribute in C# ?


Attribute is the piece of information which is generally used to pass message to developer whenever he/she is going to use that class, method or properties in his application.

Suppose you have created some .dll or Framework which one you have exposed to developer. Now you have written some new method with new features. Now you want to inform to developers that “please use the new method for better performance”. Then you can take help of attribute in C#.

attribute

Generally we will get this message in .net F/w if you will use some old method which is currently no more in use.

For using the attribute we can use Obsolete keyword and pass the required message to developer as per as given below code.

Attribute1

Note: If we have to completely restrict the end user to use that method in his application then you can pass true in obsolete method as given below images

Attribute2

Now end user developer cannot use the “CalculateAmt” method in his application.

Summary

In the above demo, we saw that how to use attribute in C#. It is very handy process to pass message to developer if you are going remove the old method.

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 in 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 &lt; 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”.

C# Version History


C# is the one the cool object oriented programming Language. Using this language we can develop all type of application like Web, Window, Mobile, Hybrid and Wearable device. It came in market in Jan 2002 with Visual Studio 2002. In each version they have added so many cool features which make the developer life easy.

C# 1.0

• It came in 2002 with VS 2002
• Managed and Unmanaged Code
• Garbage collection
• Basic all object oriented programming features

C# 2.0
• Generics
• Partial types
• Anonymous methods
• Volatile Keyword
• Nullable types
• Private setters (properties)
• Method group conversions (delegates)
• Static classes
• It came in 2005 i.e. VS 2005

C# 3.0
• Implicitly typed local variables
• Object and collection initializes
• Auto-Implemented properties
• Anonymous types
• Extension methods
• Query expressions
• Lambda expressions
• Expression trees
• Partial Methods
• LINQ
• It came in 2008 i.e. VS 2008

C# 4.0
• Dynamic binding (late binding)
• Named and optional arguments
• Generic co- and contravariance
• Embedded interop types
• Covariance and Contra-variance
• It came in 2010 i.e. with VS 2010

C# 5.0
• Async and Wait features
• Method Caller information
• Zip Compression
• Asynchronous file operation.
• Support of array with size more than 2GB
• It came in 2012 i.e. with VS 2012

C# 6.0
• Auto Property Initializers
• Expression-bodied Members
• Using “Static” Class Import
• Exception Filters
• String Interpolation
• Dictionary Initializer
• Await in Catch block
• Null Conditional Operator
• It came in 2015 i.e. with VS 2015