Click here to Skip to main content
15,880,427 members
Articles / Programming Languages / C#

Difference between Class and Structure in .NET

Rate me:
Please Sign up or sign in to vote.
4.74/5 (29 votes)
8 Oct 2011CPOL6 min read 167K   52   11
Difference between Class and Structure in .NET

Introduction

I hope this article will clarify doubts for those who are keenly looking for the difference between Structure and Class in .NET (C#). .NET is entirely an object oriented programming language that supports all object oriented concepts like Inheritance (only Single Inheritance supported in C#), Polymorphism (Runtime/Dynamic polymorphism, Compile time/Static polymorphism), Data Abstraction, Data hiding, Method and Operator overloading (operator overloading is also one type of polymorphism), Method Overriding, etc.

Apart from discussing about the differences between classes and structures, I will also be covering most of the basic keywords available in C# with the explanation in detail and related technical words.

Now let’s start with the differences between classes and structures step-by-step in details.

Differences between Class and Structure

  1. Classes are Reference types and Structures are Values types.

    When I say Classes are reference types, basically they will contain the address of an instance variables. For example:

    C#
    Class MyClass
    {
    Public Int DataMember; 	//By default, accessibility of class data members 
    			//will be private. So I am making it as Public which 
    			//can be accessed out side of the class.
    }

    In main method, I can create an instance of this class using new operator that allocates memory for this class and stores the base address of that into MyClass type variable.

    C#
    Static Public void Main (string [] arg)
    {
    	MyClass _myClassObject1 =new MyClass ();
    	_ myClassObject1.DataMember=10;
    	MyClass _myClassObject2 =_myClassObject1;
    	_ myClassObject2.DataMember=20;
    }

    In the above program, “MyClass _myClassObject2 =_myClassObject1” instruction indicates that both variables of type MyClass myClassObject1 and myClassObject2 will point to the same memory location. It basically assigns the same memory location into another variable of same type.

    So if any changes that we make in any one of the objects type MyClass will have an effect on another since both are pointing to the same memory location.

    _ myClassObject1.DataMember=10” at this line both the object’s data members will contain the value of 10. _ myClassObject2.DataMember=20 at this line both the object’s data member will contains the value of 20. Eventually, we are accessing datamembers of an object through pointers.

    Unlike classes, structures are value types. For example:

    C#
    Structure MyStructure
    {
    Public Int DataMember; 	//By default, accessibility of Structure data 
    			//members will be private. So I am making it as 
    			//Public which can be accessed out side of the structure.
    }
    
    Static Public void Main (string [] arg)
    	{
    	MyStructure _myStructObject1 =new MyStructure ();
    	_ myStructObject1.DataMember=10;
    	MyStructure _ myStructObject2 =_ myStructObject1;
    	_ myStructObject2.DataMember=20;
    }

    In the above program, instantiating the object of MyStructure type using new operator and storing address into _myStructObject variable of type MyStructure and assigning value 10 to data member of the structure using “_ myStructObject1.DataMember=10”. In the next line, I am declaring another variable_myStructObject2 of type MyStructure and assigning _myStructObject1 into that. Here .NET C# compiler creates another copy of _myStructureObject1 object and assigns that memory location into MyStructure variable _myStructObject2.

    So whatever change we make on _myStructObject1 will never have an effect on another variable _myStructObject2 of type MyStructrue. So that’s why we are saying Structures are value types.

    So the immediate Base class for class is Object and immediate Base class for Structure is ValueType which inherits from Object.

  2. Classes will support an Inheritance whereas Structures won’t.

    How are we saying that? And what is the reason behind that? The answer is Classes.

    It can be abstract, sealed, static, and partial and can’t be Private, Protected and protected internal.

    Why do we want to have class as Abstract?

    Abstract Abstract classes are incomplete classes, i.e., they will have combination of implemented and unimplemented methods along with data members, properties, events, delegates and indexers.

    The main idea to have class as abstract is to have only Base class that can be derivable and that will have basic functionality. As I mentioned above, we can have unimplemented method in abstract class that gives flexibility to derived classes to implement as required along with basic functionality. And also, we can’t instantiate object of abstract class. Abstract class can be with/without abstract methods. But if methods are declared as abstract in a class, that class also should be declared as abstract.

    Sealed Sealed classes are classes that are not inheritable. Methods also can be sealed, that is, those methods declared as sealed can’t be overridable, i.e., derived classed can’t override those methods. And normal classes can’t have sealed method. Sealed keyword should be declared with override keyword in the derived class' method for which base class will have virtual method.

    Why do we want to have class and method as Sealed?

    The reason to have class and method as sealed is to stop the inheritance at one level.

    Where to use sealed?

    If you think that class is not to be inherited in your design, you can use class as sealed. But sealed class can inherit from interface and class. If you think virtual method cannot to be inherited in derived class at one stage, we can declare a method with sealed+override combination.

    By default structures are sealed, that is the reason structures are not supporting inheritance.

    Why do we want to have class and methods as static?

    In your design, if you feel that a class should have a set of methods which operate only on arguments that we pass without initiating object of that class, then we can make that class as static class (Example: System.Math). Merely call those instance methods by class name.

    How this class will be loaded without creating an object?

    If your code accesses any of static class’s methods, then this is the responsibility of CLR (Common Language Runtime) to load this class into memory once which is the lifetime of your application.

    Object of static class can’t be instantiated. Why? Since static class can’t have instance constructor. Static class supports inheritance but other classes can’t inherit from static class, i.e., static classes are sealed. Classes can have static methods but static classes can’t have instance member and instance methods .if, should be declared with static keyword.

    Static class is useful when you implement Singleton Design pattern.

    What does partial modifier indicate?

    Partial key word is to declare the class as partial meant to say it splits the classes into multiple parts under the same class name in a single namespace.

    Why? So that developers can implement the functionally for the same class parallely.

    But all combined will give one class. Each split class can have instance variable, instance methods, properties, indexers, events and delegates.

    Structures can’t have modifiers like abstract, sealed, and static whereas classes can have.

    Both structure and class can have partial modifiers.

    As I mentioned earlier, structures can have method declaration but not virtual and sealed methods. Why? Since those two are essential for inheritance. Anyhow, the structure won’t support inheritance and declaring methods using those two keywords will throw compile time errors.

  3. Classes can have explicitly parameterless constructors whereas structures can’t.
  4. Member variable initialization is possible in class whereas in Structures, it is not.
  5. It is not possible to declare destructor in structure but in class it is possible.
  6. Process of converting structure type into object type is called boxing and process of converting object type into structure type is called unboxing.

    Example: int a=10;

    C#
    Object ob = (object) a; 	//Boxing
     a= (int) obj; 		//Unboxing
  7. The “this” keyword gives different meaning in structure and class. How?
    1. In class, “this” keyword is classified as value type of class type within which it is used like inside instance constructor or instance method.
    2. In structure, “this” keyword is classified as variable type of structure type within which it is used.

When to Use Structure and Class?

In general, classes can be used when you have more complex behavior or data. And if you think that these behaviour or data to be modified after creating an instance of class, then classes are absolute methods.

Structures can be used for small data structures. If developer feels that data members of structure cannot to be modified after creating structure, then having structure will suit.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer Melange Systems Pvt Ltd - Wireless Controls in Act
India India
I am Vijayaragavan and working as an Engineer(Application development) in Wireless Product based company in Bangalore,India.I started learning programming in Q-Basic when not even aware of what is computer and programming language and then slowly moved to C,C++,Java and Dot net.

If you wish to contact me regarding any queries about my articles please feel free to send an e-mail to vijay.crinoid@gmail.com

Enjoy Sharing Knowledge!

Vijayaragavan S

Comments and Discussions

 
QuestionWell explanation Pin
abd_Jameel13-Apr-16 15:31
abd_Jameel13-Apr-16 15:31 
GeneralMy vote of 5 Pin
Renju Vinod21-Sep-14 18:21
professionalRenju Vinod21-Sep-14 18:21 
GeneralRe: My vote of 5 Pin
yanmercal13-Jul-15 19:21
yanmercal13-Jul-15 19:21 
GeneralMy vote of 5 Pin
ardvisoor6-Aug-13 9:02
ardvisoor6-Aug-13 9:02 
It was very well defined.
GeneralMy vote of 5 Pin
Sathiyanath11-Jul-13 19:57
Sathiyanath11-Jul-13 19:57 
GeneralSaying thanks Pin
parthipan from chennai16-Jan-12 17:46
parthipan from chennai16-Jan-12 17:46 
QuestionC++ developer new in C# Pin
VHGN16-Oct-11 23:56
VHGN16-Oct-11 23:56 
Suggestion.Net is a language? Pin
Trellium16-Oct-11 15:33
Trellium16-Oct-11 15:33 
GeneralRe: .Net is a language? Pin
Vijayaragavan Srinivasan22-Oct-11 3:27
Vijayaragavan Srinivasan22-Oct-11 3:27 
QuestionC# supports multiple Inheritance through Interface Pin
AndieDu11-Oct-11 14:44
AndieDu11-Oct-11 14:44 
SuggestionHeap and Stack Pin
torial11-Oct-11 9:29
torial11-Oct-11 9:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.