Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I enforce a contract within a struct

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?

like image 438
user703016 Avatar asked Nov 27 '11 18:11

user703016


People also ask

How are smart contracts enforced?

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.

What are the structuring of a contract?

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.

What is struct in smart contract?

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”

Are smart contracts legally binding?

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.


1 Answers

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.

like image 191
Mathias Avatar answered Sep 19 '22 01:09

Mathias