Correct treatment for default structs

81 views Asked by At

I'm currently facing a problem where it would be interesting if there is a better solution. Assume, I have a struct:

public readonly struct PixelSpacing
{
    public static readonly PixelSpacing Empty = new PixelSpacing(0f,0f);

    public readonly float X;
    public readonly float Y;

    public PixelSpacing (float x, float y)
    {
      X = x;
      Y= y;
    }
}

How do I discover in a function parameter if it has been a default?

public void SetPixelSpacing (PixelSpacing pixelSpacing = default)

Of course I could this

public void SetPixelSpacing (PixelSpacing pixelSpacing? = default)
{
  PixelSpacing spacing = PixelSpacing.Empty;

  if (pixelSpacing != null)
    spacing = pixelSpacing.Value;

  ...  
}

But it seems a bit weird to me to do it like this. Even though I could use it I need to distinguish between a default constructor and some user created structure, since the default constructor of a struct and the Empty class member are the same, I cannot distinguish where it comes from, so my intention was:

public readonly struct PixelSpacing
{
    public static readonly PixelSpacing Empty = new PixelSpacing(0f,0f);
    private readonly bool IsInstance;

    public readonly float X;
    public readonly float Y;

    public PixelSpacing (float x, float y)
    {
      IsInstance = true;
      X = x;
      Y = y;
    }

    public override bool Equals(object obj)
    {
        if (!(obj is PixelSpacing pixelSpacing))
            return false;

        return Equals(pixelSpacing);
    }

    public bool Equals(PixelSpacing other)
    {
        // Check for Empty
        if (!IsInstance && !other.IsInstance)
            return true;

        return
            (Math.Abs(X - other.X) < float.Epsilon) &&
            (Math.Abs(Y - other.Y) < float.Epsilon);
    }             
}

so that I can do this:

public void SetPixelSpacing (PixelSpacing pixelSpacing = default)
{
  PixelSpacing spacing = PixelSpacing.Empty;

  if (!pixelSpacing.Equals(default)
    spacing = pixelSpacing;

  ...  
}

But then I have an extra member only for this tiny little problem.

As this is only an example I need to distinguish in some cases where the behavior of default is different to the behavior of a manually created struct. This is especially the case where the numbers initialized by the default constructor are different from the numbers of an Empty struct. Especially in the case where there are also string items that needs to be initialized differently in the user created struct than in the default struct.

How would you solve it?

0

There are 0 answers