Reputation: 1378
Hi iam trying to put my code contract on interface on my class and i write something like this:
[ContractClass(typeof(MyClassContract))]
interface IMyClass
{
int Id { get; set; }
}
[ContractClassFor(typeof(IMyClass))]
sealed class MyClassContract : IMyClass
{
public int Id
{
get { return Id; }
set { Contract.Requires(value > 0); }
}
}
public class MyClass : IMyClass
{
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
}
but don't like to be forced to define a get in contract that will be never used, mean that i can write it as
get { return "abcdrdkldbfldsk"; }
and don't like to be forced to use public property in an internal class only because cant write
get { return ImyClass.Id; }
EDIT: this is what i would like to write:
[ContractClassFor(typeof(IMyClass))]
sealed class MyClassContract : IMyClass
{
int IMyClass.Id
{
set { Contract.Requires(value > 0); }
}
}
Upvotes: 1
Views: 1216
Reputation: 107267
If you add a Contract invariant in the ContractClassFor
(MyClassContract
):
[ContractInvariantMethod]
private void ObjectInvariant ()
{
Contract.Invariant (Id >= 0);
}
Then an Ensures
/ Requires
pair will be added on the get / sets for the property. (Ref 2.3.1 of the reference)
You can then use an automatic property in the ContractClassFor
int Id { get; set; }
(i.e. will still need to add the property, because of the interface)
More here
Upvotes: 2