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

Difference Between Class and Structure in C#


C# C# 
Ratings:
0 Comment(s)
 1125  View(s)
Rate this:

Difference between Class and Structure in C#      

There are many differences between class and structure as below:


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.

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

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

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

    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();
}
}

Don't want to miss updates? Please click the below button!

Follow MindStick