Is this a good candidate for a struct?
Consider this immutable struct example where the constructor validates input and stores the validated data as a single "routing code":
struct RoutingCode
{
private readonly string routingCode;
RoutingCode(string prefix, string service, string sender)
{
// Validate prefix, service, sender strings
// ...
if (isInvalid) throw ArgumentException();
//
this.routingCode = prefix + service + sender;
}
// Gets the validated routing code.
public string Routing
{
return this.routingCode;
}
public int RoutingLength
{
return this.routingCode.Length;
}
}
This simplified example appears to me to be a good candidate for using a struct instead of a class:
- It is immutable.
- It represents a singular value.
- The instance size is small.
The problem is that all structs have an implicit default constructor. In this example, the default constructor RoutingCode() would instantiate an object where the Routing property returns null—which is an invalid routing code. This is a different from other structs such as Point or BigInteger where the backing fields contain a very logical and valid "zero" for default instances.
In addition to not ensuring a valid routing code, the RoutingLength property throws a NullReferenceException if called on a default instance.
What are the arguments for keeping this a struct versus making it a class?
class. All input is appreciated.stringis a reference type, the struct here doesn't really do much in the way of efficiency anyway.