I am trying to avoid multiple instances of a class being created with the same internal data. I tried an implementation with a separate class for building the MCode but trying to protect the MCode constructor did not work so I have come back to this implementation. I wonder if this is good design or what better solution there may be?
public class MCode : IEquatable<MCode>
{
private readonly static List<MCode> Instances;
public AEnum AE { get; }
public byte C { get; }
public BEnum BE { get; }
public static MCode GetMCode(AEnum ae, BEnum be, byte c)
{
if (Instances==null)
{
Instances = new List<MCode>();
var newmc = new MCode(ae, be, c);
Instances.Add(newmc);
return newmc;
}
var mc = Instances.Find(x => x.Equals(ae, be, c));
if (mc == null)
{
var newmc = new MCode(ae, be, c);
Instances.Add(newmc);
return newmc;
}
return mc;
}
protected MCode(AEnum ae, BEnum be, byte c)
{
AE = ae;
BE = be;
C = c;
}
public new bool Equals(MCode mc)
{
return (GetHashCode() == mc.GetHashCode());
}
public new bool Equals(AEnum ae, BEnum be, byte c)
{
return (GetHashCode() == GetHashCode(ae, be, c));
}
public new int GetHashCode()
{
return ((byte)AE * 256 * 256 + (byte)BE * 256 * C);
}
public static int GetHashCode(AEnum ae, BEnum be, byte c)
{
return ((byte)ae * 256 * 256 + (byte)be * 256 * c);
}
}
The motivations for this are that I have multiple instances of classes which contain the same MCode property and I'd like them all to be using the same read-only MCode instance.