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?

Was it helpful?

Solution 2

Found my answer here. Appearantly it isn't yet supported by Code Contracts.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top