tags:

views:

57

answers:

3

I am currently reading Effective C# and found the following line very confusing:

Last, but certainly not least, you can use interfaces to create const and nonconst versions of an interface:

What are and nonconst versions of an interface? And where would we use this?

Supporting code:

public interface IConstNameValuePair
{
  object Name
  {
    get;
  }

  object Value
  {
    get;
  }
}
public interface INameValuePair
{
  object Value
  {
    get;
    set;
  }
}

// Usage:
public class Stuff : IConstNameValuePair, INameValuePair
{
  private string _name;
  private object _value;

  #region IConstNameValuePair Members
  public object Name
  {
    get
    {
      return _name;
    }
  }

  object IConstNameValuePair.Value
  {
    get
    {
      return _value;
    }
  }

  #endregion

  #region INameValuePair Members

  public object Value
  {
    get
    {
      return _value;
    }
    set
    {
     _value = value;
    }
  }
  #endregion
}
+2  A: 

It is showing that, through one of those interfaces, you can't actually modify the value (the 'set' property isn't defined). It's a little dubious to call this 'const', as that is actually a keyword that has special meaning. But that's what the author means.

Noon Silk
Dumb me. I overlooked part of code. Thank you.
Sandbox
+1  A: 

What are and nonconst versions of an interface?

I think he means 'const' and 'non-const' in the way that a C++ programmer would understand them, i.e. as follows.

A 'const' interface is an interface whose properties you can't alter. For example in the following code, the test1 method can get but cannot set the properties of the stuff instance.

A 'non-const' interface is an interface whose properties you can alter, for example the test2 method can set as well as get the properties of the stuff instance.

void test()
{
  Stuff stuff = new Stuff();
  test1(stuff);
  test2(stuff);
}

void test1(IConstNameValuePair stuff)
{
}

void test2(INameValuePair stuff)
{
}
ChrisW
A: 

First you need to be clear that the choice of names used (const and nonconst) is very poor. Const typically refers to the idea that a value is constant, meaning it cannot be changed.

Looking at the two interfaces, the IConstNameValuePair defines only a get property accessor. When you have an instance of Stuff that has been cast to an IConstNameValuePair then you effectively have an unchangeable instance because through the interface there is no way to change the values.

The INameValuePair interface defines both a get and a set property accessor. When you have an instance of Stuff that has been cast to an INameValuePair then you effectively have a changeable instance because through the interface you can change the values.

That being said, there are certainly better approaches to solve this problem than using two different interfaces.

Scott Dorman