C# Workshop – Interfaces

Standard

Interfaces

An interface is defined in a similar way to a class but there are no keywords such as public and private nor are the statement blocks for a Method present and their name should start with I for Interface, Classes can implement many Interfaces, but only Inherit from a one class.

To use an interface in dotnetfiddle.net enter the following:

using System;
namespace Workshop
{
	public interface IShape
	{		
		double Area();
	}

	public class Shape
	{		
		public int Height { get; set; }
		public virtual double Area() 
		{
			return 0;
		}
	}
	
	public class Rectangle : Shape
	{
		public int Width { get; set; }
		public override double Area()
		{
			return (Height * Width);
		}
	}
		
	public class Demo
	{	
		public static void Main()
		{
			Rectangle rectangle = new Rectangle()
			{
				Height = 10,
				Width = 15
			};
			Console.WriteLine(rectangle.Area());
		}	
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s