Search:

Custom Search
_________________________________________________________________

Thursday, July 31, 2008

Implementing Interfaces in C#

Interfaces are a set of methods, properties and event that provides functionalities. This interces can be implemented by C# classes or structures.

Interfaces do not provide methods of their own. They only contain methods identifiers, return values and parameters.
This is very useful when you have certain behaviour that need to follow a set of operations, such as manipulating a Data Base.
C# classes are allowed to implement many interfaces.

Implementing an Interfaz in a class says that the class must provide implementation to all of the methods signatures from the interface.

Let’s write a small C# example. In this example you will see of to implement interfaces that contain methods signatures and how a class implements this interface.

Code:

interface Interface1
{

void Method1();
void Method2();

}

public class Class1 : Interface1
{

public void Method1()
{

//Implementation of the method
}

public void Method2() { }

}

Now, you can also use interfaces that the .NET Frameworks has. In this example you will see how to implement the Idisposable interface. The Idisposable interface supports a method called Dispose(). It also supports a constructor and a destructor.

Also you will see in the Main class, the keyword using. It is used to create a new object and can be manipulated only within the braces ({}). After the close brace is reached, the object will be automatically destroyed.

Code:

class Class2 : IDisposable
{

public Class2()
{

Console.WriteLine("Constructor");
}

~Class2()
{

Console.WriteLine("Destuctor");
}

public void Dispose()
{

Console.WriteLine("Dispose from IDisposable.Dispose");
}

}


Main:

class Program
{

static void Main(string[] args)
{

using (Class2 myC = new Class2()) { }
}
}

Console:


1 comment:

ankur said...

I'll try to follow this method and will post you my feed back.



Voucher Codes