Tag Archives: C#

Extension Methods

They are static methods that can be invoked like an instance method. Static methods can be declared only in Static classes. Let’s see how extension methods are declared.
public static void ExportToExcel(this DataSet ds)
{
//do something…
}

Extension methods are declared by specifying the “this” keyword as the modifier in the first parameter. The ExportToExcel method is declared as an extension method for the DataSet class.
Extension methods are invoked as soon the namespace of the containing static class is included.
In the below code snippet, the extension method is declared inside
namespace Orcas.Samples
{
public static class Extensions
{
public static void ExportToExcel(this DataSet ds)
{
//do something…
}
}
}

Above method is invoked in the client program as,
using Orcas.Samples;
DataSet ds = new DataSet();
ds.ExportToExcel();

Advertisements

Leave a comment

Filed under C#

Auto-Implemented Properties

Auto-Implemented Properties

In C# 2.0 properties are declared as follows:

private int iEmpId;
private string strEmpName;

public int EmpId
{
get { return iEmpId; }

set { iEmpId = value; }
}

Samething is redfined in C#3.0 using auto-implemented properties like:
public class AutoProperties
{
public int EmpID { get; set; }
public string EmpName { get; set; }
public int Age { get; private set; } // read-only
}
Behind the scene, compiler automatically creates private, anonymous fields that can be accessed from the above auto-implemented properties.

Leave a comment

Filed under C#