What are the uses of structure in C# programming and also differentiate between class and structure with example?

Asked 25-Aug-2021
Viewed 547 times

0

What are the uses of structure in C# programming and also differentiate between class and structure with example?


1 Answer


0

Structure
A structure is a user defined data type, Structure in C# is a Value Type Data Type. It helps you to create data related to a convertible hold of different data types. struct Keyword is used to create the structure and used to represent a record.
Like Enumeration, Structure is also a User Defined Type. But Structure is not only Name/Value Pair like Enumerations but they are similar to Class Type, which can have both Data Members and Methods, whereas the basic difference between Class and Structure is that Structure is Value Type, whereas Class There are reference types.
We can understand the structure in a way as Light Weight Class. But Structure is in a way Implicitly Sealed Type, which cannot be inherited whereas Classes can be inherited.
Syntax 
struct struct_name

 {
  //member variable
  //function
  //operator
  //events
  //delegates
 }
using System	

public struct Coords
{
public double X { get; }
public double Y { get; }
public Coords(double x, double y)
{
        this.X = x;
        this.Y = y;
}
public override string ToString() => $'({X}, {Y})';
}
public class Program
{
 public static void Main()
 {
  Coords coor=new Coords(12.5,23.0);
  Console.WriteLine(coor.ToString());
 }
}
Output
(12.5, 23)

Difference between Class and Structure

 Structure Class
Structs are of value types in C#.Classes are of reference types in C#.
value types are allocated on stack memory.reference types are allocated on heap memory.
Allocation and de-allocation is cheaper in value type as compare to reference type.Allocation of large reference type is cheaper than allocation of large value type.
Struct can create an instance, with or without new keyword.Classes used new keyword for creating instances.