Creating a Custom Value Type
Question
Can we create our own value type?
Short interview answer
Yes. Define a
structor anenum. A struct is a value type and can encapsulate data and related behavior.
Detailed answer
Use a struct for a small, data-centric value such as a coordinate, amount, or identifier:
public readonly record struct CustomerId(Guid Value);
var first = new CustomerId(Guid.NewGuid());
var second = first; // Copies the value.
Immutable structs avoid surprising copy-and-mutate behavior. A struct can implement interfaces, but it cannot inherit from a class or another struct and cannot be a base class.