I’m working on a class called PByte, which should represent an int value between 32 an 126. (PByte = Printable Byte.)
Now I want to prevent the user of the class to initializing an object incorrectly, but I don’t want to throw an exception, I just want that Visual Studio doesn’t compile, like it happens when you try to do this: byte b = 256;
sealed class PByte : IEquatable<PByte>, IComparable, IComparable<PByte>
{
public PByte(int value)
{
/* if (value < 32 || value > 126)
throw new ArgumentException("\"" + value + "\" is not a valid PByte-value"); */
this._value = value;
}
[...]
I’ve also implemented this:
[...]
public static implicit operator PByte(int value)
{
/* if (value < 32 || value > 126)
throw new ArgumentException("\"" + value + "\" is not a valid PByte-value"); */
return new PByte(value);
}
}
So this should also be impossible:
PByte p = 2000;
You can’t enforce that at compile time without using code contracts. Even then, I think the code contracts only produce warnings and general puts the ownership of the problem on the calling scope.