How to protect the library user from false initialization?

I am working on a dll that contains a type that shoul can represent an integer value from 32 to 126 and is called "PByte" (for a byte to print). The problem is that I want to protect the user from type initialization, for example. 1000. This should not cause an exception. It should prevent compilation, for example, Visiual Studio tries to initialize, for example, a byte with 256. The type is initialized in the constructor.

public PByte(int value) { /* if (value < 32 || value > 126) throw new ArgumentException("\"" + value + "\" is an invalid value!"); */ this._value = value; } 

it

 PByte pb = new PByte(2000); 

cannot be compiled.

+4
source share
2 answers

Do you want a compilation exception to be thrown at runtime? It's impossible!

Should PByte pb = new PByte(get399()); compile? No, but how do you know what get399() does without running the program?

But first of all, you must specify the byte parameter. This will result in compile-time exceptions for numbers outside of 0-255.

+5
source

The only option you have is to assign a null character that is out of range. Something like that.

 public struct PByte : IEquatable<PByte> { readonly byte _value; public PByte(byte value) { this._value = (byte)( value > 31 && value < 128 ? value : 0); } public byte Value { get { return this._value; } } public char Char { get { return (char)_value; } } public bool Equals(PByte other) { return _value.Equals(other._value); } } class Program { static void Main(string[] args) { var p1 = new PByte(1000); // Won't compile var p2 = new PByte(5); //'\0' var p3 = new PByte(65); //'A' var p4 = new PByte(125); //'}' var p5 = new PByte(175); //'\0' } } 
+2
source

All Articles