As per the documentation:
Because structure types have value semantics, we recommend you to define immutable structure types.
Option 1
If your Car
type's properties don't need to change at runtime, they should not have any public setters. You can simplify population of a new Car
by adding a constructor or by using one of the other options described in the docs.
static class Program
{
static void Main(string[] args)
{
Car c1 = new Car(
// c1's data
brand: "Bugatti",
model: "Bugatti Veyron EB 16.4",
color: "Gray");
// c1's data
// Displaying the values
Console.WriteLine(//"Name of brand: " + c1.Brand +
"\nModel name: " + c1.Model +
"\nColor of car: " + c1.Color);
Console.ReadLine();
}
}
public struct Car
{
public Car(string brand, string model, string color)
{
Brand = brand ?? throw new ArgumentNullException(nameof(brand));
Model = model ?? throw new ArgumentNullException(nameof(model));
Color = color ?? throw new ArgumentNullException(nameof(color));
}
// Declaring different data types
public string Brand { get;}
public string Model { get; }
public string Color { get; }
}
Option 2
Use a class
instead of a struct
.
static void Main(string[] args)
{
Car c1 = new Car(
// c1's data
model: "Bugatti Veyron EB 16.4",
color: "Gray")
{ Brand = "Bugatti" };
// c1's data
// Displaying the values
Console.WriteLine(//"Name of brand: " + c1.Brand +
"\nModel name: " + c1.Model +
"\nColor of car: " + c1.Color);
Console.ReadLine();
}
}
public class Car
{
public Car(string model, string color)
{
Model = model ?? throw new ArgumentNullException(nameof(model));
Color = color ?? throw new ArgumentNullException(nameof(color));
}
// Declaring different data types
public string Brand { get; set; }
public string Model { get; }
public string Color { get; }
}
Since one of the main benefits of using struct
is to allocate fixed sizes of data on the stack (using stackalloc
) and you are using string
properties (which are not a fixed size), the most sensible option is to use a class
for this scenario. Whether you actually need a constructor, use property setters, or logical defaults depends on whether your application will deal with the values if they are null
and/or default.