Michael,
I want to create a type that behaves like in integer but only allows
assignment of say 3 digit integers where attempts to assign values greater or
loess will throw an exception. E.g. int threeDigitInteget = 7; will throw an
exception.
I can achive this behaviour through the new types constructor but cannot
work out how to intercept assignments using the = assignment operator.
If you by three digit integer mean that the value must be 100-999 then
something like this will almost get you there
struct MyInt
{
private int _value;
public MyInt(int value)
{
if ( value < 100 || value > 999 )
throw new ArgumentOutOfRangeException(...);
_value = value;
}
public static implicit operator MyInt(int value)
{
return new MyInt(value);
}
// ... add more operators to make it behave like int ...
}
MyInt mi = 123;
The biggest problem here is that value types can always be zero
initialized with the default constructor, so you can't prevent _value
from being set to zero.
But if you mean that
MyInt mi = 001;
should work but
MyInt mi = 1;
shouldn't, then you can't do it.
Mattias
--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ |
http://www.dotnetinterop.com
Please reply only to the newsgroup.