Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use the C# new keyword to expand properties on an interface?

I understand how the "new" keyword can hide methods in a derived class. However, what implications does it have for classes that implement interfaces that use the keyword?

Consider this example, where I decide to expand an interface by making its properties read/write.

public interface IReadOnly {

   string Id {
      get;
   }
}

public interface ICanReadAndWrite : IReadOnly  {

   new string Id {
      get;
      set;
   }
}

Then you are able to do things like this:

public IReadOnly SomeMethod() {
   // return an instance of ICanReadAndWrite
}

Is this bad design? Will it cause issues for my classes that implement ICanReadAndWrite?

Edit: Here is a contrived example of why I might want to do something like this:

Say I have a factory class that returns an IShoppingCartItemReadWrite. I can then have a service layer that manipulates prices on it, changes stuff, etc. Then, I can pass these objects as IShoppingCartItemReadOnly to some kind of presentation layer that won't change them. (Yes, I know it technically can change them-- this is a design question, not security, etc.)

like image 495
user10789 Avatar asked Sep 09 '09 12:09

user10789


1 Answers

It's not a particularly bad idea. You should be aware that the implementor can (if it implicitly implements the interface, then a single read/write property could satisfy both interfaces) provide two distinct implementations:

class Test : ICanReadAndWrite {
   public string Id {
      get { return "100"; }
      set { }
   }
   string IReadOnly.Id {
      get { return "10"; }
   }
}

Test t = new Test();
Console.WriteLine(t.Id);  // prints 100
Console.WriteLine(((IReadOnly)t).Id); // prints 10

By the way, in general, the new inheritance modifier does nothing except to tell the compiler to shut up and don't throw out a "you're hiding that member" warning. Omitting it will have no effect in the compiled code.

like image 67
mmx Avatar answered Oct 08 '22 04:10

mmx