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:
- Class Sample
- {
- public int add(int x,int y)
- {
- return (x + y);
- }
-
-
-
- }
- class Test
- {
- public void Main(string[] args)
- {
- Sample obj = new Sample();
- obj.add(5, 10);
- }
- }
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:
- struct Sample
- {
- public int id;
- public string name;
- public string city;
- }
- class Test
- {
- static void Main(string[] args)
- {
- Sample obj;
- obj.id = 1;
- obj.name = "Magesh";
- obj.city = "Bangalore";
- Console.WriteLine("Id "+obj.id + "Name: " + obj.name + "City: " + obj.city);
- }
- }
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.