3.2.6 - Records and fields (C#)
Group differently typed information about one entity and use its named fields in a solution. Required written answers are native C#; execution is unavailable here, with an optional Python demonstration for exploration.
Grouping related fields
A record groups related named fields describing one entity, and the fields can have different data types.
Record
A data structure containing named fields that belong together, such as a car's registration, price and number of doors.
A car's make, model and registration are strings. Its price can be real and its door count integer. Putting every value in an integer array would lose the strings; making every value text would lose convenient numeric processing. Named fields describe the roles directly.
A C# struct can implement this record concept. The definition below goes at class/file scope, outside Main; it defines the structure of a Car, not a particular car's values. public makes these simple fields accessible to the code using a Car.
struct Car
{
public string Make;
public string Model;
public string Registration;
public double Price;
public int NumberOfDoors;
}
The generic specification term record does not require using C#'s newer record keyword. A suitable struct or class with the required fields can represent the data. Separate Car values follow the same field layout but describe different cars.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account