codescracker


c#

C# Classes



« Previous Tutorial Next Tutorial »


Whenever you define a class in C#, you define a blueprint for the data type. Objects are the instances of a class. And the methods and variables that constitute a class, called as members of that class.

Define a Class in C#

To define a class in C#, use class keyword followed by the class name and then the class body enclosed inside the pair of curly braces. Here is the general form to define a class in C#:

access-specifier class class-name
{
	// member variables of the class
	access-specifier data-type variable-name1;
	access-specifier data-type variable-name2;
	access-specifier data-type variable-name3;
	.
	.
	.
	access-specifier data-type variable-nameN;
	
	// member methods of the class
	access-specifier return-type method-name1(parameter-list)
	{
		// body of the method
	}
	access-specifier return-type method-name2(parameter-list)
	{
		// body of the method
	}
	access-specifier return-type method-name3(parameter-list)
	{
		// body of the method
	}
	.
	.
	.
	access-specifier return-type method-nameN(parameter-list)
	{
		// body of the method
	}
}

Here is the explanation of the above general form of class definition in C#:

C# Class Example

Here is an example program, illustrates the concept and use of class in C#:

/* C# Classes - Example Program */
		
using System;
namespace ClassExample
{
		class BoxClass
		{
		public double len;
		public double bre; 
		public double hei;
		}
		class Tester
		{
			static void Main(string[] args)
			{
				Box b1 = new Box();
				Box b2 = new Box();
				double vol = 0.0;
	
				b1.hei = 5.0;
				b1.len = 6.0;
				b1.bre = 7.0;
	
				b2.hei = 10.0;
				b2.len = 12.0;
				b2.bre = 13.0;
			
				vol = b1.hei * b1.len * b1.bre;
				Console.WriteLine("Box1 Volume = {0}",  vol);	
	
				vol = b2.hei * b2.len * b2.bre;
				Console.WriteLine("Box2 Volume = {0}", vol);
			
				Console.ReadKey();
			}
		}
}

Now, when we compile and run the above program, it will produce the following output:

Box1 Volume = 210
Box2 Volume = 1560

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test