I'd like to enforce a struct to always be valid regarding a certain contract, enforced by the constructor. However the contract is violated by the default
operator.
Consider the following, for example:
struct NonNullInteger
{
private readonly int _value;
public int Value
{
get { return _value; }
}
public NonNullInteger(int value)
{
if (value == 0)
{
throw new ArgumentOutOfRangeException("value");
}
_value = value;
}
}
// Somewhere else:
var i = new NonNullInteger(0); // Will throw, contract respected
var j = default(NonNullInteger); // Will not throw, contract broken
As a workaround I changed my struct to a class so I can ensure the constructor is always called when initializing a new instance. But I wonder, is there absolutely no way to obtain the same behavior with a struct?
A smart contract is a self-enforcing agreement embedded in computer code managed by a blockchain. The code contains a set of rules under which the parties of that smart contract agree to interact with each other. If and when the predefined rules are met, the agreement is automatically enforced.
A commercial contract follows a typical structure starting with the parties to the contract who are the people entering into the agreement. This is usually followed by the recitals which provide some background to the agreement.
Structs are custom data types that can group several variables. They represent a record of “something”. Suppose you want to keep a list of “To Do's” and need to know if they are completed. One would keep a simple list and create a Struct: item “To Do”
In general, smart contracts are enforceable as long as they follow the basic rules of contractual agreements. These include the following. As with any agreement, there must be an offer, an acceptance of that offer and consideration. Put simply, these are defined thusly.
I don't see how you could do this, because, unlike a class, a struct always has a default parameterless constructor; given the way your struct is written, a value of 0 cannot be prevented:
Structs cannot contain explicit parameterless constructors. Struct members are automatically initialized to their default values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With