How to keep the user from incorrect variable initialization?

I am working on a PByte class that should represent an int value between 32 and 126. (PByte = Printable Byte.) Now I want the class user to not initialize the object incorrectly, but I do not want to throw an exception, I just want Visual Studio not to compile , as it happens when trying 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 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;

+4
source share
2 answers

You cannot force this at compile time without using code contracts. Even then, I think that code contracts only generate warnings, and general ones put ownership of this problem in the call area.

+5
source

Basically, you can do this using Code Contracts in combination with editor extensions (available in the extensions gallery). However, I am not sure that he will fully enforce each situation. (Edit: enable static validation in the Code Contracts section of the project properties.)

So, roughly speaking, you can do something like this:

 public PByte(int value) { Contract.Requires<ArgumentException>(value >= 32 && value <= 126, "\"" + value + "\" is not a valid PByte-value"); this._value = value; } 
+1
source

All Articles