Within the C# programming language, an object could be both a price kind or a reference kind. Whereas a variable of a price kind comprises its worth, a variable of a reference kind comprises a reference to an object, or a reference to an occasion of the sort.
The important thing distinction between a price kind and a reference kind is within the task semantics. Moreover, as a result of a price kind is all the time “copied by worth,” if you move a price kind as a parameter to a way or assign it to a variable, your entire knowledge is copied. In contrast, if you assign a reference kind, solely the reference is copied; each references level to the identical object within the reminiscence.
C# additionally lets us create what’s known as worth objects, a particular kind of object utilized in domain-driven design that enables us to articulate area ideas merely, clearly, and concisely. On this article we’ll study worth objects, focus on their advantages, and illustrate how we will use them in C#.
Create a console software venture in Visible Studio
First off, let’s create a .NET Core console software venture in Visible Studio. Assuming Visible Studio 2022 is put in in your system, observe the steps outlined under to create a brand new .NET core console software venture.
- Launch the Visible Studio IDE.
- Click on on “Create new venture.”
- Within the “Create new venture” window, choose “Console App (.NET Core)” from the checklist of templates displayed.
- Click on Subsequent.
- Within the “Configure your new venture” window, specify the identify and placement for the brand new venture.
- Click on Subsequent.
- Within the “Further data” window, select “.NET 8.0 (Lengthy Time period Help)” because the framework model you need to use.
- Go away the “Don’t use top-level statements” and the “Allow native AOT publish” verify containers unchecked.
- Click on Create.
We’ll use this .NET 8 console software venture to work with worth objects within the subsequent sections of this text.
What are worth objects in C#?
Within the C# language, a price object is outlined as an object that may be recognized solely by the state of its properties. Worth objects symbolize a descriptive side of a website with out having an identification. In different phrases, worth objects symbolize parts of the design that we care about solely by way of their contents, not their identities.
In domain-driven design (DDD), the worth object sample represents objects with out identification and helps equality based mostly on their attributes. It must be famous right here that opposite to worth objects, entity objects have distinct identities. In contrast to entity objects, that are outlined by their identification and have mutable state, worth objects are outlined by their attributes and are immutable.
Immutability means you can not change a price object as soon as it has been created; any operations carried out on worth objects will create a brand new occasion as an alternative. The immutability of worth objects has vital efficiency advantages. As a result of two worth objects are thought-about equal in the event that they include equivalent values, even when they may be totally different objects, they turn out to be interchangeable. In different phrases, immutability allows object reuse.
A price objects instance in C#
Contemplate the next class named Deal with, which comprises just a few properties and an argument constructor.
public class Deal with { public string HouseNo { get; set; } public string Road { get; set; } public string ZipCode { get; set; } public string Metropolis { get; set; } public Deal with(string houseno, string road, string zipCode, string metropolis) { HouseNo = houseno; Road = road; ZipCode = zipCode; Metropolis = metropolis; } }
You possibly can create an occasion of this class and assign values to its properties utilizing the next code.
Deal with handle = new Deal with("505", "Woodland Road", "CR2 8EN", "London");
Nevertheless, as a result of the Deal with class right here exposes public setters, you possibly can simply change the values of its properties from exterior the category. This violates one of many fundamental options of worth objects, particularly its help for immutability.
We are able to repair this by redesigning the Deal with class as proven under.
public class Deal with { public string HouseNo { get; non-public set; } public string Road { get; non-public set; } public string ZipCode { get; non-public set; } public string Metropolis { get; non-public set; } public Deal with(string houseno, string road, string zipCode, string metropolis) { HouseNo = houseno; Road = road; ZipCode = zipCode; Metropolis = metropolis; } }
As you’ll be able to see above, the properties of our new Deal with class include non-public setters, which don’t permit adjustments to the worth of any of those properties from exterior the category, thereby preserving immutability. In case you execute this program, you’ll be greeted with the error proven in Determine 1 under.
Determine 1. Worth objects are immutable.
You can even implement worth objects utilizing information in C#. To do that, you employ the report key phrase to outline a report kind that encapsulates knowledge a lot the identical approach we did with the Creator class earlier. The next code snippet reveals how one can outline a report kind in C#.
public report Deal with(string Houseno, string Road, string ZipCode, string Metropolis);
Greatest practices for utilizing worth objects in C#
When working with worth objects in C#, you need to observe these greatest practices:
- Implement correct equality checks based mostly on worth to forestall inconsistencies and errors.
- Use worth objects to symbolize ideas within the area mannequin solely if you really feel it’s acceptable.
- Use worth objects judiciously as a result of they’ve efficiency overheads.
- Contemplate implementing validation logic inside your worth object constructor to implement enterprise guidelines and constraints when the worth object is created.
- Adhere to beneficial patterns and naming conventions to make sure readability, consistency, and readability in your worth object implementations.
Worth objects encapsulate primitive varieties and have two essential properties, i.e., they don’t have an identification and they’re immutable. Worth objects can simplify advanced knowledge constructions by encapsulating associated knowledge right into a single unit. This ensures knowledge integrity, enforces robust typing, reduces errors, and improves the readability of the supply code. You possibly can make the most of worth objects to boost the readability and maintainability of your C# code by offering a extra expressive illustration of the area ideas.
Sometimes, creating worth objects in C# includes overriding equality comparability and implementing acceptable value-based semantics. A typical observe includes overriding the Equals() and GetHashCode() strategies, and offering different operators for comparability. Sometimes, we use a base class that includes these strategies that each one worth object implementations ought to prolong.
Within the above instance, I’ve supplied a fundamental implementation of worth objects in C#. In a future put up right here, I’ll discover how we will implement a price object base class and focus on extra superior ideas.
Copyright © 2024 IDG Communications, Inc.