Class and Struct Explained in C#

Introduction

 
The intention of this blog is to share the uses of and differences between class and struct in C#. 
 

Class:

 
A class is a reference type. A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects. A Class keyword is used to declare a class. A class can access specifiers (public or internal, etc...), but class-default access to modifiers is internal. A Class creates an object then implements the members.

Examples:

  1. Class Sample  
  2. {  
  3. public int add(int x,int y)  
  4. {  
  5. return (x + y);  
  6. }  
  7.   
  8.   
  9.   
  10. }  
  11. class Test  
  12. {  
  13. public void Main(string[] args)  
  14. {  
  15. Sample obj = new Sample();  
  16. obj.add(5, 10);  
  17. }  
  18. }  

Struct:

A structure is a value data type and is particularly useful for small data values. A "Struct" keyword is used to declare the structure. Struct cannot have a permission default constructors or destructors. Structs can be instantiated directly without a new operator, and can implement different interfaces.

Examples:

  1. struct Sample  
  2. {  
  3. public int id;  
  4. public string name;  
  5. public string city;  
  6. }  
  7. class Test  
  8. {  
  9. static void Main(string[] args)  
  10. {  
  11. Sample obj;  
  12. obj.id = 1;  
  13. obj.name = "Magesh";  
  14. obj.city = "Bangalore";  
  15. Console.WriteLine("Id "+obj.id + "Name: " + obj.name + "City: " + obj.city);  
  16. }  
  17. }  

Differences between class and struct:

Class

- A class is a reference type.
- A class is can create an object to use that class.
- Class reference types are allocated on heap memory 
- A class can be abstract
- Contains permission default constructors or destructors
- Generally used for large programs 
 
Struct
 
- A struct is a value data type.
- A struct can create an object, without new keywords.
- Struct value types are allocated on stack memory.
- A struct can’t be abstract
- Doesn't have permission default constructors or destructors.
- Generally used for small programs.