codescracker


c#

C# Inheritance



« Previous Tutorial Next Tutorial »


Using inheritance in C#, you can define a class in terms of another class, that makes it easier in creating and maintaining the application. On creating a class, instead of writing completely new data members and member functions, you can designate that, new class should inherit the members of an existing class. This existing class is called as base class, and the new class is called as derived class.

C# Base Class and Derived Class

Here is the general form to create derived class in C#:

access-specifier class base-class
{
	.
	.
	.
}
class derived-class : base-class
{
	.
	.
	.
}

C# Inheritance Example

Here is an example, demonstrates the concept and use of inheritance in C#:

/* C# Inheritance - Example Program */
		
using System;
namespace InheritanceExample
{
	class InheritanceClass	// base class
	{
		public void initializeWidth(int w)
		{
			wid = w;
		}
		public void initializeHeight(int h)
		{
			hei = h;
		}
		protected int wid;
		protected int hei;
	}

	class Rect: InheritanceClass	// derived class
	{
		public int calculateArea()
		{ 
			return (wid * hei); 
		}	
	}
	
	class RectTester
	{
		static void Main(string[] args)
		{
			Rect r = new Rect();
	
			r.initializeWidth(5);
			r.initializeHeight(7);
	
			Console.WriteLine("Area = {0}",  r.calculateArea());
			
			Console.ReadKey();
		}	
	}
}

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

Area = 35

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test