C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Interview   Jobs   Projects   Offshore Development    
Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Revenue Sharing | Talk to Us |



My Profile

Gifts

Active Members
TodayLast 7 Days more...







Difference between class and struct in C#


Posted Date: 10 Dec 2004    Resource Type: Articles    Category: .NET Framework

Posted By: Dhyanchandh.A.V       Member Level: Gold
Rating:     Points: 10




Introduction:

1. Classes are reference types and structs are value types.

Since classes are reference type, a class variable can be assigned null.But we cannot assign null to

a struct variable, since structs are value type.


struct AStruct
{
int aField;
}
class AClass
{
int aField;
}
class MainClass
{
public static void Main()
{
AClass b = null; // No error.
AStruct s = null; // Error [ Cannot convert null to 'AStruct'

because it is a value type ].

}
}


2. When you instantiate a class, it will be allocated on the heap.When you

instantiate a struct, it gets created on the stack.

3. You will always be dealing with reference to an object ( instance ) of a class. But

you will not be dealing with references to an instance of a struct ( but dealing directly

with them ).

4. When passing a class to a method, it is passed by reference. When passing a

struct to a method, it's passed by value instead of as a reference.

5. You cannot have instance Field initializers in structs.But classes can have

initializers.


class MyClass
{
int myVar =10; // no syntax error.
public void MyFun( )
{
// statements
}
}
struct MyStruct
{
int myVar = 10; // syntax error.
public void MyFun( )
{
// statements
}
}

6. Classes can have explicit parameterless constructors. But structs cannot have

explicit parameterless constructors.



class MyClass
{
int myVar = 10;
public MyClass( ) // no syntax error.
{
// statements
}
}

struct MyStruct
{
int myVar;
public MyStruct( ) // syntax error.
{
// statements
}

7. Classes must be instantiated using the new operator. But structs can be

instantiated without using the new operator.

MyClass aClassObj; // MyClass aClassObj=new MyClass(); is the correct

format.

aClassObj.myVar=100;//NullReferenceException(because aClassObj does not contain a

reference to an object of type myClass).


MyStruct aStructObj;
aStructObj.myVar=100; // no exception.

face="verdana"size="2">
8. Classes support inheritance.But there is no inheritance for structs.
( structs don't support inheritance polymorphism )

So we cannot have a base structure and a derived structure.

(1)
struct MyStruct
{
int aStructVar;
internal void aStructMethod()
{
// statements
}
}
class MyClass : MyStruct // Syntax error.
{
int aClassVar;
int aClassMethod()
{
// statements
}
}

(2)
class MyClass
{
int aClassVar;
int aClassMethod()
{
// statements
}
}

struct MyStruct : MyClass // Syntax error.
{
int aStructVar;
internal void aStructMethod()
{
// statements
}
}

Note : Like classes, structures can implement interfaces

9. Since struct does not support inheritance, access modifier of a member of a struct cannot be protected or protected internal.

10. It is not mandatory to initialize all Fields inside the constructor of a class.
But all the Fields of a struct must be fully initialized inside the constructor.

class MyClass //No error( No matter whether the Field ' MyClass.myString ' is

initialized or not ).

{
int myInt;
string myString;

public MyClass( int aInt )
{
myInt = aInt;
}
}

struct MyStruct // Error ( Field ' MyStruct.myString ' must be fully assigned

before it leaves the constructor ).

{
int myInt;
string myString;

public MyStruct( int aInt )
{
myInt = aInt;
}
}

11. A class is permitted to declare a destructor.But a struct is not

permitted to declare a destructor.

struct MyStruct
{
int myInt;
public MyStruct( )
{
}
~MyStruct( ) //Error.
{
Console.WriteLine("Destructor of MyStruct object");
}
}

class MyClass
{
int myInt;
public MyClass( )
{
}
~MyClass( ) // No Error.
{
Console.WriteLine("Destructor of MyClass object");
}
}

12. classes are used for complex and large set data. structs are simple to use.

structs are useful whenever you need a type that will be used often and is mostly just a

piece of data.

A Sample Code:



using System;
class MainClass
{

static void Main( )
{
Console.WriteLine( "Struct \n" );
MyStruct var1=new MyStruct( );

var1.Member="Initialized";

// value of var1 is assigned to var2
MyStruct var2=var1;// stmt --> [A]

//var1.str & var2.str are different memory locations in the stack.
Console.WriteLine(var1.Member+"\n"+var2.Member);
Console.WriteLine( "---------------" );

var1.Member="Assigned";
Console.WriteLine( var1.Member+"\n"+var2.Member );

Console.WriteLine( "\nClass\n" );
MyClass obj1=new MyClass( );

obj1.Member="Initialized";

// reference(or simply address)of an object stored in obj1 is assigned to

obj2.

MyClass obj2=obj1;// stmt --> [B]

//obj1 & obj2 are 2 reference variables in the stack.They points to a

single object
//in the heap.So obj1.str & obj2.str represent same memory location in the heap.

Console.WriteLine( obj1.Member+"\n"+obj2.Member );
Console.WriteLine( "---------------" );

obj1.Member="Assigned";
Console.WriteLine( obj1.Member+"\n"+obj2.Member );
}
}

public struct MyStruct
{
string str;
public string Member
{
get
{
return str;
}
set
{
str=value;
}
}
}

public class MyClass
{
string str;
public string Member
{
get
{
return str;
}
set
{
str=value;
}
}
}

Output:
Struct

Initialized
Initailized
---------------
Assigned
Initailized

Class

Initialized
Initailized
---------------
Assigned
Assigned

Summary:

Through this article I tried to enumerate certain differences of Classes and

Structures in C#.

In the Sample Code: I have made an attempt to show the difference in output
when similar statements are executed, first time for a struct( in stmt --> [A] ) and second

time for a
class( in stmt --> [B] ).

If you have any suggestions or found any errors in this article, please mail me.









Responses

Author: Rajasekaran Ponnusamy    28 Dec 2004Member Level: Silver   Points : 0
Its very very nice and good article. Its very useful to me


Author: Ravi Makwana    06 Jan 2005Member Level: Bronze   Points : 0
Feeling previlidged after gone through this article.
Keep up the same style for all the articles you may post in future!!!

Regards,



Author: srinivasu julakanti    09 Jan 2005Member Level: Bronze   Points : 0
Good job done in compiling the differences b/w struc and class.
It would be great if you could write articles in more advanced topics like differences b/w Web services & Remoting. Delegates , ADO.NET


Author: Evren TURKOGLU    26 Feb 2005Member Level: Bronze   Points : 0
It is very good for me. Before i can confuse which one can be used in my project. Thanks very much...


Author: Amrit Pal Singh    04 Apr 2007Member Level: Bronze   Points : 0
Great Job!
it seems lot of efforts behind thisarticle.


Author: Viyyapu Venkata Ramesh    24 Oct 2007Member Level: Silver   Points : 0
Very Good Article ,


Author: mukesh chauhan    24 Mar 2008Member Level: Gold   Points : 0
Good article on oops


Author: kala    05 May 2008Member Level: Bronze   Points : 2
It's a very nice article, i have never seen such clear explanation in any other material especiallly difference between classes and struct.


Author: Vijaykumar Patil    05 May 2008Member Level: Gold   Points : 2
very nice article


Author: Saravanan    04 Jun 2008Member Level: Silver   Points : 1
Very nice, thanks for this article, good job friend...


Author: Payal Mani Jain    05 Jun 2008Member Level: Gold   Points : 0
very nice article


Author: Mahesh Raj    07 Jun 2008Member Level: Gold   Points : 1
This is very good information,Continue posting such useful articles.


Author: Umid    19 Jun 2008Member Level: Bronze   Points : 1
It is kind of useful article. I liked for instance...


Author: Gaurav Agrawal    19 Jun 2008Member Level: Gold   Points : 2
Hi,
Greetings.
Really great article.
You have explained difference very clearly with example.
It is very good question for freshers to face interview .
It is frequently asked question in interview.
Keep Posting and help your fellow developers.

Regards
Gaurav Agrawal


Author: Kapil Dhawan    19 Jun 2008Member Level: Gold   Points : 2
Hello
Nice piece of code
Thanks for sharing your knowledge with us.
I hope to see more good article from your side
This code is going to help lots of guys.
Ton Thanks to you
Regards,
Kapil



Author: Ramkumar    20 Jun 2008Member Level: Bronze   Points : 0
nice post
thanks


Author: Satyanarayan SushilKumar Bajoria    20 Jun 2008Member Level: Gold   Points : 2
Hi,
It's really a nice piece of information regarding structure and class.
It clarify all my doubt regarding structure and class.
Keep posting such descriptive article with example.


Author: Siddesh Kapadi    21 Jun 2008Member Level: Silver   Points : 2
Great article sorts out lots of issues regarding the difference. Just would be great if you give the example of when to use which and what are the elements that can be declared in a structure like properties, events, etc...


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: What is a Assembly and Whats the difference between private and shared assemblies
Previous Resource: How to start and stop windows services programmatically
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
Related Resources



Read TATA Nano reviews.
dotNet Slackers   BizTalk Adaptors    Web Design   Scripts
Are you waiting for engineering entrance result? Watch here for engineering entrance results.
budget conference call

Contact Us    Privacy Policy    Terms Of Use