Windows Phone Developers

Thursday, October 30, 2008

How to Create Interfaces in .NET / Interfaces in .NET

How to Create Interfaces in C# / Interfaces in C#

An interface defines a set of members, such as properties and procedures that classes and structures can implement. The interface defines only the signatures of the members and not their internal workings.

Interface definitions are enclosed within the Interface and End Interface statements in Visual Basic, they are enclosed within parenthesis in C# (as shown below). Following the Interface statement, you can add an optional inherited interface name.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace CSharpSample

{

interface IRetail

{

string BrandName();

}

}

A class or structure implements the interface by supplying code for every member defined by the interface. Finally, when the application creates an instance from that class or structure, an object exists and runs in memory.

Interface can be used only at namespace or module level. That is, the declaration context for an interface must be a source file, namespace, class, structure, module, or interface. Interface cannot be a declared in a procedure or block.

To implement the interface in a class, suffix class name by a colon and the interface name as shown below

class ClsTea : IRetail

The class ClsTea should implement the methods described in the Interface. Otherwise Compiler Error CS0535 will be thrown -

'class' does not implement interface member 'member'

class ClsTea : IRetail

{

//Variables

private string _locale;

private static string _brand;

// Property

public static string Brand

{

get

{

return _brand;

}

set

{

_brand = value;

}

}

//property

public string Locale

{

get { return _locale; }

set { _locale = value; }

}

private string[] brands = new string[12];

public string this[int index]

{

get { return brands[index]; }

set { brands[index] = value; }

}

public string BrandName()

{

return "N/A";

}

}

}

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

No comments:

Post a Comment

kbAlertz.com :: Visual Studio 2005

kbAlertz.com :: Visual Studio 2008

kbAlertz.com :: Visual Basic 2005