Difference between Classes and Structs in C#

 

Structure has no identity and it is always in accessible state and Sturct does not have any added behaviour. Whereas Class has identity but not in accessible state and it has added behaviour.  Main difference between Structs and Classes is Structs are Value types whereas Classes are Reference types. 

In this article we discuss about main difference between Class and Structs in C#. 

Structs in C#: 

First we create the sample Struct Employee as shown below. 

struct Employee 

{ 

        public int EmpId; 

        public string EmpName; 

} 

As shown above Employee Struct has no identity. If you have two Employees both representing the same Employee record, the program will behave exactly the same regardless of which one you use. Generally in Software entities with no identity are called value Types. There are predefined values in C#, those are int, bool, decimal, and all Struct types, are called value types in C#. Value types contain accessible state and have no added behaviour. Variables of the Struct type are allowed to contain methods, but it is recommended that they do not because those represent same values for all variables and they will contain only data. However, it is perfectly reasonable to define operators in structs. Operators are stylized methods that do not add new behaviour.

 

Classes in C#: 

Create sample Class Company as shown below.

 

class Company 

{ 

        private void GetEmployees() 

         

        } 

}

 

As shown above Company class has identity. If you create two objects for Company class, the program will behave differently depending on which one you use. In Software orld entities that have identity are called objects. Types represented by classes are called reference types in C#. Classes in C# are Reference types. As compared with Structs, nothing but methods should be visible in a class. These methods add extra high-level behaviour beyond the primitive behaviour present in the lower-level inaccessible data.