C# .NET Core records can have methods. Records in C# were introduced in C# 9.0 as a feature for creating immutable reference types with value-like semantics. They are often used to represent data objects that primarily contain data without much behavior. However, despite being focused on data, records can still have methods, just like classes.
Methods in Records
You can define methods in a record just as you would in a class. This allows you to add behavior to your record types, making them more versatile. Here’s a simple example:
record Person(string FirstName, string LastName)
{
public string FullName() => $"{FirstName} {LastName}";
public void PrintGreeting()
{
Console.WriteLine($"Hello, my name is {FullName()}!");
}
}
In this example, the Person
record has a FullName
method that concatenates the FirstName
and LastName
properties, and a PrintGreeting
method that prints a greeting to the console.
Key Points to Note:
- Immutability: By default, the properties of a record are immutable (read-only after initialization). This means that while you can define methods that operate on the data within the record, these methods typically do not modify the state of the record.
- With-expressions: One of the key features of records is the
with
expression, which allows you to create a copy of a record with some properties modified. Methods that operate on records might leverage this feature to return new instances with altered data rather than modifying the existing instance. - Instance and Static Methods: Like classes, records can have both instance methods (which operate on a particular instance of the record) and static methods (which operate at the type level and are not tied to a particular instance).
- Expression-bodied Members: You can use expression-bodied members, as shown in the
FullName
method above, to keep method definitions concise. - Record Structs: Starting with C# 10.0, you can also define record structs (
record struct
), which are value types. These can also have methods.
Example with a with
Expression:
csharpCopy codepublic record Person(string FirstName, string LastName)
{
public string FullName() => $"{FirstName} {LastName}";
public Person WithLastName(string newLastName) => this with { LastName = newLastName };
}
In this example, the WithLastName
method uses the with
expression to return a new Person
record with a modified LastName
, leaving the original instance unchanged.
Conclusion
C# records can definitely have methods, allowing you to encapsulate behavior within these data-focused types. This flexibility makes records a powerful feature in C#, balancing the simplicity of data objects with the potential for more complex behavior when needed.
Leave a Reply