blog

Home / DeveloperSection / Blogs / Difference Between Class and Structure in C#

Difference Between Class and Structure in C#

Anupam Mishra 2832 16-Dec-2015
There are many differences between class and structure as below:


1 A class is a group of objects that has common properties and it is a template or blueprint from which objects are created.But in structure, it is a value type datatype that helps you to make a single variables hold related data of  various datatype.

2 In class you can define constructor as well as destructor.But in structure, you cannot define default constructor (it’s created automatically when you create structure instance. Instead of default you can use parameterized constructor in structure) and destructor are not allowed here.

 3 In class you can use inheritance but in structure you don’t inherit other structure.

 4 In class, you can implement more than one interfaces as same as in structure.

 5 In structure member can’t be specifies as abstract virtual or protected access specifier. But in class you can does.

 6 In class only static member and member function are no need to depend upon class instances.But in structure if you are not using new keyword then the field remained unassigned & the object can’t be used until all the fields are initialized.

Syntax of Structure:
struct Student{
private string name;
……………………
//defining members or methods
};
Syntax of class:
<Access Specifier > class <Class_Name>
{
// Member variables
<Access Specifier><data type> var1;
<Access Specifier><data type> var1;
……………………………………….
//Defining default Constructor
 
Public <Class_Name>(){
     //default constructor invoked
}
// defining parameterized constructor
Public <Class_Name>(<data type varn>){
     //parameterized constructor invoked
}
//destructor declaration
~<Class_Name>(){
    //Destructor is invoked
}
//method declaration
<Access Specifier><return type>Method1(parameter_list)
{
   //Method body
}
//defining main for starting execution or entry point
static void main(string[] args)
{
// creating instance of class & automatically called default constructor itself
<Class_Name> ob1=new <Class_Name>();
//for calling parameterized constructor
<Class_Name> ob2=new <Class_Name>(<data type var1>);
//calling static methods
Method1(<data type var1>);
//waiting for pressing keys
Console.Readkey();
}
}

c# c# 
Updated 13-Mar-2018

Leave Comment

Comments

Liked By