codescracker


c#

C# Interfaces



« Previous Tutorial Next Tutorial »


Interface is simply a syntactical contract that all the classes inheriting the interface should follow. Interfaces defines the properties, methods, and events, which are the members of the interface.

C# Interface Declaration

Interface in C#, are declared simply by using the keyword interface. Here is an example, showing how to declare interface in C#:

public interface TransactionExample
{
   // these are the interface members
   void displayTransaction();
   double calculateAmount();
}

C# Interface Example

Here is an example program, to understand the concept and use of interface in C#:

/* C# Interface - Example Program */
		
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
namespace InterfaceExample
{
	public interface TransactionExample
	{
		void displayTransaction();
		double getAmountMethod();
	}	
	public class Transaction : TransactionExample
	{
		private string tCode;
		private string date;
		private double amount;
		public Transaction()
		{
			tCode = " ";
			date = " ";
			amount = 0.0;
		}
		public Transaction(string strcode, string strdate, double damount)
		{
			tCode = strcode;
			date = strdate;
			amount = damount;
		}
		public double getAmountMethod()
		{
			return amount;
		}  
		public void displayTransaction()
		{
			Console.WriteLine("Transaction Code = {0}", tCode);
			Console.WriteLine("Transaction Date = {0}", date);
			Console.WriteLine("Transaction Amount = {0}", getAmountMethod());
		}
	}
	class Tester
	{
		static void Main(string[] args)
		{
			Transaction t1 = new Transaction("001", "8/11/2013", 78900.00);
			Transaction t2 = new Transaction("002", "9/11/2013", 451900.00);
			t1.displayTransaction();
			t2.displayTransaction();
			Console.ReadKey();
		}
	}
}

Now when we compile and run the above program then we will get the following output:

Transaction Code = 001
Transaction Date = 8/11/2013
Transaction Amount = 78900
Transaction Code = 002
Transaction Date = 9/11/2013
Transaction Amount = 451900

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test