Found my answer here. Appearantly it isn't yet supported by Code Contracts.
Ensure interface readonly property does not change
-
25-09-2022 - |
Question
Consider the following interface:
interface IToto
{
string Name {get;}
}
Using Code Contracts, how can I make sure that the Name property value never changes?
I tried using Contract.OldValue
within a ContractInvariantMethod
-marked method but appearantly it isn't supported. Anything else I can do?
La solution 2
Autres conseils
This isn't possible using just interfaces. However, you can use an interface with an abstract class to get what you want. An abstract class allows you to define functionality but you cannot instantiate it. So in your real class you can inherit from the abstract class and you get your defined functionality automatically.
Take a look at this:
namespace ConsoleApplication1
{
public interface IMyThing
{
string Name { get; }
}
public abstract class MyThingBase : IMyThing
{
public string Name {
get
{
return "Mystringvalue";
}
}
}
public class MyThing : MyThingBase
{
//stuff
}
}
Then:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var myObject = new MyThing();
Console.Write(myObject.Name);
}
}
}
This prints: Mystringvalue
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow