Struct vs. Record vs. Class in C# | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (173).NET Core  (29).NET MAUI  (203)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (211)BoldSign  (13)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (65)Flutter  (132)JavaScript  (219)Microsoft  (118)PDF  (81)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (897)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (50)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (127)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (618)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (39)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (501)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (42)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (381)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (17)Web  (582)What's new  (323)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Struct vs. Record vs. Class in C#

Struct vs. Record vs. Class in C#

C# is an object-oriented programming language developed and maintained by Microsoft that is being used to create desktop, web, and mobile apps. Struct, class, and record are three user-defined data types that differ from one another with inherent use cases.

In this article, I will compare and contrast these user-defined data types in C# with some examples to make it easier for you to understand.

Class

Class in C# is a reference type. For reference types, the default equals implementation provides reference equality. Reference equality states that the compared object references relate to the same object. They refer to the exact heap location.

Let’s declare a class in C#.

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Use the keyword class to create a class in C#. You can specify an access modifier (private, public, protected, internal), if required, for the class.

Let’s create an object for the defined class and assign values for the class properties. Use the dot operator to access the properties of the instance of the class.

Refer to the following code example.

Person person = new Person();
person.Age = 30;
person.Name = "Neymar Jr";
Console.WriteLine(person.Name+" "+person.Age); // Neymar Jr 30

Let’s now create another object for the same class person using the first object created.

var person1 = person;
person1.Age = 29;
Console.WriteLine(person.Name+" "+person.Age); // Neymar Jr 29
Console.WriteLine(person1.Name+" "+person1.Age); // Neymar Jr 29

Here, though we update the age property of the object person1, the same property of the person object is updated. This is due to the fact that class in C# is a reference type. That is, both objects refer to the same place in the memory where actual data is stored.

In other words, object references will be saved in a stack memory, and values will be saved in a heap memory. In this example, two object references represent one value in the heap memory. So, we get the same value for the properties of the two objects.

When to use class

  • When you need to create complex objects that have state, behavior, and need to be extended by inheritance.
  • When implementing interfaces, use abstract classes.
  • When you need to take advantage of polymorphism.

Explore the best and most comprehensive Blazor UI components library in the market.

Struct

The struct data structure is similar to the class but is a value data type. Its instances and objects are stored on a stack. It is used to encapsulate a small group of related variables.

Let’s declare a struct in C#.

struct Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Use the struct keyword to declare the struct (structure) in C#. You can use access modifiers, if required.

Let’s create an object of the struct Person.

Person person = new Person();

Now, access the struct’s properties and assign them values using the dot operator, as in the code example.

Person person = new Person();
person.Age = 30;
person.Name = "Neymar Jr";
Console.WriteLine(person.Name+" "+person.Age); // Neymar Jr 30

We have created a struct object for the struct person. Now, create another struct object using the object created in the previous code.

var person1 = person;
person1.Age = 29;
Console.WriteLine(person.Name+" "+person.Age); // Neymar Jr 30
Console.WriteLine(person1.Name+" "+person1.Age); // Neymar Jr 29

The struct object person1 was created from the object person. The change in the value of the property of person1 did not affect the value of the object person. This is because struct is a value type of data structure. They represent different locations in the memory for each object.

When to use struct

  • When the scope of the object is small.
  • When the data group is small and simple.
  • When needing better performance for the system.

Everything a developer needs to know to use Blazor components in the Blazor app is completely documented.

Record

The record type was introduced in version 9.0 of C#. It provides an immutability feature with which to work. So, record types are immutable by default. The record is also a reference type that behaves identically to the value type when it relates to value equality.

Let’s declare a record in C#.

public record Person( string Name, int Age );

Now, create a record object. When creating the object for the record, you must pass values as parameters to the constructor.

Person person = new Person("Neymar Jr", 30);
Console.WriteLine(person.Name+" "+person.Age); // Neymar Jr 30

You can also access properties of the record using the dot operator, as in the code example.

You can print the names and values of properties just by using the object, like in the following code, for the record type.

Console.WriteLine(person); // Person { Name = Neymar Jr, Age = 30 }

Record type using with expression

We can make properties of a class immutable using the init property, so we cannot change the values of the properties.

class Person
{
    public string Name { get; init; }
    public int Age { get; init; }
}

We have to create a new object whenever we need to assign values to the properties declared with init. These properties that can be set on a class only once during object initialization are known as init-only properties. Moreover, if you attempt to set them again later, a C# compiler error will occur.

When we need to create hundreds of properties using this concept, it won’t be easy to manage. But we can prevent this issue by using the record type with the With expression.

Refer to the following code.

var person1 = person with {Age = 29};
Console.WriteLine(person); // Person { Name = Neymar Jr, Age = 30 }
Console.WriteLine(person1); // Person { Name = Neymar Jr, Age = 29 }

When to use the record type

  • Record types are suitable when your data doesn’t need to change (is immutable).
  • The record type will benefit data transfer objects if they have one-way flow.

Explore the different application UIs developed using Syncfusion Blazor components.

Conclusion

In this article, we discussed three user-defined data types, class, struct, and record, and when to use each of them in your code. I hope you found this article helpful. Please share your feedback in the comments below.

Thank you for reading!

Syncfusion provides more than 1,800 components and frameworks to ease app development on various platforms. We encourage you to evaluate the components and use them as needed for application development:

BlazorFlutter
ASP.NET CoreASP.NET MVC
ASP.NET Web FormsJavaScript
AngularReact
VuejQuery
.NET MAUIXamarin
UWPWinForms
WPFWinUI
Excel LibraryPDF Library
Word LibraryPowerPoint Library

If you have any questions or comments, you can contact us through our support forumssupport portal, or feedback portal. As always, we are happy to assist you!

Related blogs

Tags:

Share this post:

Comments (2)

Ludovico Abagnale
Ludovico Abagnale

Semplice e preciso.
Ottimo articolo
Grazie

C# v10 (released November 8, 2021) “adds record structs so that you can define records as value types”
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/records

so this article (May 18, 2023) is incomplete and should be updated. Suggest you change
from
Person person = new Person();
person.Age = 30;
person.Name = “Neymar Jr”;
to
Person person = new Person() {Age = 30, Name = “Neymar Jr”};

and that you change both Age and Name in each of later examples for better explanation

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed