What is the best way to implement polymorphic behavior in classes that I can't modify? I currently have some code like:
if(obj is ClassA) {
// ...
} else if(obj is ClassB) {
// ...
} else if ...
The obvious answer is to add a virtual method to the base class, but unfortunately the code is in a different assembly and I can't modify it. Is there a better way to handle this than the ugly and slow code above?
Hmmm... seems more suited to Adapter.
public interface ITheInterfaceYouNeed
{
void DoWhatYouWant();
}
public class MyA : ITheInterfaceYouNeed
{
protected ClassA _actualA;
public MyA( ClassA actualA )
{
_actualA = actualA;
}
public void DoWhatYouWant()
{
_actualA.DoWhatADoes();
}
}
public class MyB : ITheInterfaceYouNeed
{
protected ClassB _actualB;
public MyB( ClassB actualB )
{
_actualB = actualB;
}
public void DoWhatYouWant()
{
_actualB.DoWhatBDoes();
}
}
Seems like a lot of code, but it will make the client code a lot closer to what you want. Plus it'll give you a chance to think about what interface you're actually using.
Check out the Visitor pattern. This lets you come close to adding virtual methods to a class without changing the class. You need to use an extension method with a dynamic cast if the base class you're working with doesn't have a Visit method. Here's some sample code:
public class Main
{
public static void Example()
{
Base a = new GirlChild();
var v = new Visitor();
a.Visit(v);
}
}
static class Ext
{
public static void Visit(this object b, Visitor v)
{
((dynamic)v).Visit((dynamic)b);
}
}
public class Visitor
{
public void Visit(Base b)
{
throw new NotImplementedException();
}
public void Visit(BoyChild b)
{
Console.WriteLine("It's a boy!");
}
public void Visit(GirlChild g)
{
Console.WriteLine("It's a girl!");
}
}
//Below this line are the classes you don't have to change.
public class Base
{
}
public class BoyChild : Base
{
}
public class GirlChild : Base
{
}
I would say that the standard approach here is to wrap the class you want to "inherit" as a protected instance variable and then emulate all the non-private members (method/properties/events/etc.) of the wrapped class in your container class. You can then mark this class and its appropiate members as virtual so that you can use standard polymorphism features with it.
Here's an example of what I mean. ClosedClass is the class contained in the assembly whose code to which you have no access.
public virtual class WrapperClass : IClosedClassInterface1, IClosedClassInterface2
{
protected ClosedClass object;
public ClosedClass()
{
object = new ClosedClass();
}
public void Method1()
{
object.Method1();
}
public void Method2()
{
object.Method2();
}
}
If whatever assembly you are referencing were designed well, then all the types/members that you might ever want to access would be marked appropiately (abstract, virtual, sealed), but indeed this is unfortunately not the case (sometimes you can even experienced this issue with the Base Class Library). In my opinion, the wrapper class is the way to go here. It does have its benefits (even when the class from which you want to derive is inheritable), namely removing/changing the modifier of methods you don't want the user of your class to have access to. The ReadOnlyCollection<T> in the BCL is a pretty good example of this.
Take a look at the Decorator pattern. Noldorin actually explained it without giving the name of the pattern.
Decorator is the way of extending behavior without inheriting. The only thing I would change in Noldorin's code is the fact that the constructor should receive an instance of the object you are decorating.
Extension methods provide an easy way to add additional method signatures to existing classes. This requires the 3.5 framework.
Create a static utility class and add something like this:
public static void DoSomething(this ClassA obj, int param1, string param2)
{
//do something
}
Add a reference to the utility class on the page, and this method will appear as a member of ClassA. You can overload existing methods or create new ones this way.
Related
public class BaseClass
{
public virtual void Display()
{
Console.WriteLine("I am Base Class");
}
public void BaseClassMethod()
{
Console.WriteLine("I am Base Class Method");
}
}
public class DerivedClass : BaseClass
{
public override void Display()
{
Console.WriteLine("I am Derived Class");
}
public void DerivedClassMethod()
{
Console.WriteLine("I am Derived Class Method");
}
}
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
bc.Display();
bc.BaseClassMethod();
Console.WriteLine("--------------");
DerivedClass dc = new DerivedClass();
dc.Display();
dc.BaseClassMethod();
dc.DerivedClassMethod();
Console.WriteLine("--------------");
BaseClass bc2 = new DerivedClass();
bc2.Display();
bc2.BaseClassMethod();
//bc2.DerivedClass(); --> I can't reach b2.DerivedClass() method
Console.ReadLine();
}
}
Hi everyone. I am trying to clear my mind about Why and where would I want to create and use derived class object from base class reference. I know how virtual works. I know derived class is a base class and I can override virtual methods. I can reach non virtual methods in base class. But I want to know where could and why would I want to use this style of object creation. Like in my last part of the example code;
BaseClass bc2 = new DerivedClass();
I can't reach derived class methods so I cant use derived class methods. But it is still derived class because of the new DerivedClass. If I use normal DerivedClass d = new DerivedClass(); style, I can use both class methods. I just cant find any reason and situation I would want to use this style. I would be glad if anyone show me in which situation I have to use derived class object from base class reference so I can understand this style is exist in language. I want to know WHY, I am not asking why this isn't working or something like that. Just want to know situations. Thank you.
There are two main usages:
1) Collections of multiple types
Lets change your example a little bit
public class Shape
{
public virtual void Display()
{
Console.WriteLine("I am a Shape");
}
public void BaseClassMethod()
{
Console.WriteLine("I am Base Class Method");
}
}
public class Square : Shape
{
public override void Display()
{
Console.WriteLine("I am Square");
}
public void DerivedClassMethod()
{
Console.WriteLine("I am Derived Class Method");
}
}
public class Circle : Shape
{
public override void Display()
{
Console.WriteLine("I am Circle");
}
}
class Program
{
static void Main(string[] args)
{
List<Shape> shapes = new List<Shape();
shapes.Add(new Square());
shapes.Add(new Circle());
I have a list that can hold Circles, Squares, and generic Shapes all in a single collection.
2) Polymorphism
Continuing on from the previous code
foreach(Shape shape in shapes)
{
shape.Display();
}
we don't know what kind of Shape the variable shape is, however we do know that whatever kind it is it will have a Display() method we can call and it will show the correct information.
Polymorphism is useful when you need to call a function on something but you don't know the specific type that something will be because you are pulling a collection of base types like above, or you want to write a function that can take in any kind of Shape because the function does not need to know the specific kind to do it's work.
public static void LogDisplay(Shape shape)
{
Console.WriteLine("I am about to call shape.Display()");
shape.Display();
Console.WriteLine("I am just called shape.Display()");
}
My favorite example, because people can understand the use, is logging. Imagine I create a website. When I'm developing the site, I want to log to my file system, because it's easy to access. When I deploy the website, I want to log to the event log, because maybe I don't have direct access to the file system on that machine.
However, I only want to change where things are logged, I want the base class to structure how the actual text looks. So I have my base class that formats text:
public abstract class BaseLogger
{
public abstract void LogException(Exception ex);
public abstract void LogUserMessage(string userMessage);
protected string GetStringFromException(Exception ex)
{
//....
}
protected string GetStringFromUserMessage(string userMessage)
{
//....
}
}
Now I can have a class that logs to the File System:
public class FileLogger : BaseLogger
{
public FileLogger(string filename)
{
//initialize the file, etc
}
public override void LogException(Exception ex)
{
var string = GetStringFromException(ex);
File.WriteAllLines(...);
}
public override void LogException(Exception ex)
{
var string = GetStringFromUserMessage(ex);
File.WriteAllLines(...);
}
}
and my class that logs to the Event Log:
public class EventLogger : BaseLogger
{
public EventLogger()
{
//initialize the eventlog, etc
}
public override void LogException(Exception ex)
{
var string = GetStringFromException(ex);
EventLog.WriteEntry(...);
}
public override void LogException(Exception ex)
{
var string = GetStringFromUserMessage(ex);
EventLog.WriteEntry(...);
}
}
Now in my program, I only care that I have a BaseLogger when I inject one into my classes. The implementation details are irrelevant, I just know that I can LogException and LogUserMessage no matter what I'm using.
When I'm using the logger I benefit from not caring which derived class I use. That's the benefit of treating each derived class like a base class. I can swap them out without my program caring.
There are many reasons to do this, mostly to do with code re-usability and extensiblity, which in other words, to make a small change or enhancement easily without needing to rewrite a whole lot.
A real world example (which happens frequently) is the case where you have different customers using your software which may require you to support different databases (or even different table structures). So in order to do that, you can derive implementations from a common base class, and vary in the implementation details without affecting the rest of the program.
This also follows the design principle "Program
to an 'interface', not an 'implementation'" which is explained in the GoF design pattern book
public abstract class ProviderBase
{
public abstract Employee[] GetAllEmployees();
}
public class MySqlProvider:ProviderBase
{
public override Employee[] GetAllEmployees()
{
string select = "select * from employees";
//query from mysql ...
}
}
public class MsSqlProvider : ProviderBase
{
public override Employee[] GetAllEmployees()
{
string select = "select * from user u left join employee_record e on u.id=e.id";
//query from mysql ...
}
}
Then in the main program you may be able to change the type of database implementation by configuration or Dependency Injection
ProviderBase provider = null;
if(databaseType == "MySql")
{
provider = new MySqlProvider();
}
else if (databaseType == "MsSql")
{
provider = new MsSqlProvider();
}
var employees = provider.GetAllEmployees();
//do something
I believe a lot of the reasoning behind the availability of using derived classes has to do with minimizing repeated code.
To reference a real life example...
If I was to ask you to describe the attributes and abilities of a car, and then was to ask you to do the same for an electric car, you would find that much of the attributes and abilities are shared by both. So instead of having it be two completely separate classes, it would be more efficient to create the base class Car, and derive electricCar from that. Then you will only need to account for the specific differences of the electric car within the derived class, and all the shared attributes and abilities will carry over.
Hope this helps you understand the usefulness of base classes and derived classes. Very oversimplified but I feel it may help you grasp the concept!
The main reason to use a base class is reusability and polymorphism
So you could create the class depending on a condition:
BaseClass bc
if(case1)
bc = new DerivedClass1();
else
bc = new DerivedClass2();
In the following application you can use bc even if you don't know what kind of derived class it is at compile time. You can pass it e.g. to other functions and call the overridden methode:
bc.Display();
Derived class methods can only be used when you know what kind of derived class you actual have. Then you can do a conversion.
DerivedClass1 dc = bc as DerivedClass1;
dc.DerivedClassMethod()
I have a class
public class Foo{
public Foo{...}
private void someFunction(){...}
...
private Acessor{
new Acessor
}
}
with some private functionality (someFunction). However, sometimes, I want to allow another class to call Foo.SomeFunction, so I have an inner class access Foo and pass out that:
public class Foo{
public Foo{...}
private void someFunction(){...}
...
public Acessor{
Foo _myFoo;
new Acessor(Foo foo){_myFoo = foo;}
public void someFunction(){
_myFoo.someFunction();
}
}
}
With this code, if I want a Foo to give someone else pemission to call someFunction, Foo can pass out a new Foo.Accessor(this).
Unfortunately, this code allows anyone to create a Foo.Accessor initiated with a Foo, and they can access someFunction! We don't want that. However, if we make Foo.Accessor private, then we can't pass it out of Foo.
My solution right now is to make Acessor a private class and let it implement a public interface IFooAccessor; then, I pass out the Foo.Accessor as an IFooAccessor. This works, but it means that I have to declaration every method that Foo.Accessor uses an extra time in IFooAccessor. Therefore, if I want to refactor the signature of this method (for example, by having someFunction take a parameter), I would need to introduce changes in three places. I've had to do this several times, and it is starting to really bother me. Is there a better way?
If someFunction has to be accessible for classes in the same assembly, use internal instead of private modifier.
http://msdn.microsoft.com/en-us/library/7c5ka91b(v=vs.71).aspx
If it has to be accessible for classes which are not in the same assemble then, it should be public. But, if it will be used by just a few classes in other assemblies, you probably should think better how you are organizing you code.
It's difficult to answer this question, since it's not clear (to me at least) what exactly you want to achieve. (You write make it difficult for someone to inadverdantly use this code in a comment).
Maybe, if the method is to be used in a special context only, then explicitly implementing an interface might be what you want:
public interface ISomeContract {
void someFunction();
}
public class Foo : ISomeContract {
public Foo() {...}
void ISomeContract.someFunction() {...}
}
This would mean, that a client of that class would have to cast it to ISomeContract to call someFunction():
var foo = new Foo();
var x = foo as ISomeContract;
x.someFunction();
I had a similar problem. A class that was simple, elegant and easy to understand, except for one ugly method that had to be called in one layer, that was not supposed to be called further down the food chain. Especially not by the consumers of this class.
What I ended up doing was to create an extension on my base class in a separate namespace that the normal callers of my classes would not be using. As my method needed private access this was combined with explicit interface implementation shown by M4N.
namespace MyProject.Whatever
{
internal interface IHidden
{
void Manipulate();
}
internal class MyClass : IHidden
{
private string privateMember = "World!";
public void SayHello()
{
Console.WriteLine("Hello " + privateMember);
}
void IHidden.Manipulate()
{
privateMember = "Universe!";
}
}
}
namespace MyProject.Whatever.Manipulatable
{
static class MyClassExtension
{
public static void Manipulate(this MyClass instance)
{
((IHidden)instance).Manipulate();
}
}
}
I have a design issue. I am modifying existing code and where I was instantiating new class. It's giving me errors due to turning the class into a Abstract class which I can understand. It's throwing an error because you can't create instances of abstract class.
I had this code below
ExampleProcessor pro = new ExampleProcessor();
but the ExmapleProcessor class is now turned into abstract class.
public abstract class ExmapleProcessor {
public abstract void Method1();
public abstract void Method2();
}
Child classes AExampleProcessor and BExampleProcessor.
public class AExampleProcessor : ExampleProcessor
{
public override void Method1() { //do something }
public override void Method2() { //do something }
}
public class BExampleProcessor : ExampleProcessor
{
public override void Method1() { //do something }
public override void Method2() { //do something }
}
So this line is causing 42 errors "ExampleProcessor pro = new ExampleProcessor();" everywhere in my application.
I dont want to do
AExampleProcessor pro = new AExampleProcessor();
and
BExampleProcessor pro = new BExampleProcessor();
because I want my application to decide which class to use. How can I make it so it loads up the correct class?
I would like code examples please..
Create a factory:
public static class ExampleProcessorFactory
{
public static ExampleProcessor Create()
{
if(IsFullmoon)
return new ExampleProcessorA();
else
return new ExampleProcessorB();
}
}
Then replace all calls to new ExampleProcessor() with calls to ExampleProcessorFactory.Create(). Now you've encapsulated the instantiation logic and the choosing of what concrete class to instantiate into one place where you can apply any logic to decide what class to instantiate. (The logic of deciding when to use which class might benefit from some improvement to be unrelated to the full moon.)
Since you want the application to decide which concrete subclass to use, I suggest you use a Factory pattern.
That way, the client code knows only that you are using an ExampleProcessor, and the implementation details remain hidden.
Is there a construct in Java or C# that forces inheriting classes to call the base implementation? You can call super() or base() but is it possible to have it throw a compile-time error if it isn't called? That would be very convenient..
--edit--
I am mainly curious about overriding methods.
There isn't and shouldn't be anything to do that.
The closest thing I can think of off hand if something like having this in the base class:
public virtual void BeforeFoo(){}
public void Foo()
{
this.BeforeFoo();
//do some stuff
this.AfterFoo();
}
public virtual void AfterFoo(){}
And allow the inheriting class override BeforeFoo and/or AfterFoo
Not in Java. It might be possible in C#, but someone else will have to speak to that.
If I understand correctly you want this:
class A {
public void foo() {
// Do superclass stuff
}
}
class B extends A {
public void foo() {
super.foo();
// Do subclass stuff
}
}
What you can do in Java to enforce usage of the superclass foo is something like:
class A {
public final void foo() {
// Do stuff
...
// Then delegate to subclass
fooImpl();
}
protected abstract void fooImpl();
}
class B extends A {
protected void fooImpl() {
// Do subclass stuff
}
}
It's ugly, but it achieves what you want. Otherwise you'll just have to be careful to make sure you call the superclass method.
Maybe you could tinker with your design to fix the problem, rather than using a technical solution. It might not be possible but is probably worth thinking about.
EDIT: Maybe I misunderstood the question. Are you talking about only constructors or methods in general? I assumed methods in general.
The following example throws an InvalidOperationException when the base functionality is not inherited when overriding a method.
This might be useful for scenarios where the method is invoked by some internal API.
i.e. where Foo() is not designed to be invoked directly:
public abstract class ExampleBase {
private bool _baseInvoked;
internal protected virtual void Foo() {
_baseInvoked = true;
// IMPORTANT: This must always be executed!
}
internal void InvokeFoo() {
Foo();
if (!_baseInvoked)
throw new InvalidOperationException("Custom classes must invoke `base.Foo()` when method is overridden.");
}
}
Works:
public class ExampleA : ExampleBase {
protected override void Foo() {
base.Foo();
}
}
Yells:
public class ExampleB : ExampleBase {
protected override void Foo() {
}
}
I use the following technique. Notice that the Hello() method is protected, so it can't be called from outside...
public abstract class Animal
{
protected abstract void Hello();
public void SayHello()
{
//Do some mandatory thing
Console.WriteLine("something mandatory");
Hello();
Console.WriteLine();
}
}
public class Dog : Animal
{
protected override void Hello()
{
Console.WriteLine("woof");
}
}
public class Cat : Animal
{
protected override void Hello()
{
Console.WriteLine("meow");
}
}
Example usage:
static void Main(string[] args)
{
var animals = new List<Animal>()
{
new Cat(),
new Dog(),
new Dog(),
new Dog()
};
animals.ForEach(animal => animal.SayHello());
Console.ReadKey();
}
Which produces:
You may want to look at this (call super antipatern) http://en.wikipedia.org/wiki/Call_super
If I understand correctly you want to enforce that your base class behaviour is not overriden, but still be able to extend it, then I'd use the template method design pattern and in C# don't include the virtual keyword in the method definition.
No. It is not possible. If you have to have a function that does some pre or post action do something like this:
internal class Class1
{
internal virtual void SomeFunc()
{
// no guarantee this code will run
}
internal void MakeSureICanDoSomething()
{
// do pre stuff I have to do
ThisCodeMayNotRun();
// do post stuff I have to do
}
internal virtual void ThisCodeMayNotRun()
{
// this code may or may not run depending on
// the derived class
}
}
I didn't read ALL the replies here; however, I was considering the same question. After reviewing what I REALLY wanted to do, it seemed to me that if I want to FORCE the call to the base method that I should not have declared the base method virtual (override-able) in the first place.
Don't force a base call. Make the parent method do what you want, while calling an overridable (eg: abstract) protected method in its body.
Don't think there's any feasible solution built-in. I'm sure there's separate code analysis tools that can do that, though.
EDIT Misread construct as constructor. Leaving up as CW since it fits a very limited subset of the problem.
In C# you can force this behavior by defining a single constructor having at least one parameter in the base type. This removes the default constructor and forces derived types to explcitly call the specified base or they get a compilation error.
class Parent {
protected Parent(int id) {
}
}
class Child : Parent {
// Does not compile
public Child() {}
// Also does not compile
public Child(int id) { }
// Compiles
public Child() :base(42) {}
}
In java, the compiler can only enforce this in the case of Constructors.
A constructor must be called all the way up the inheritance chain .. ie if Dog extends Animal extends Thing, the constructor for Dog must call a constructor for Animal must call a constructor for Thing.
This is not the case for regular methods, where the programmer must explicitly call a super implementation if necessary.
The only way to enforce some base implementation code to be run is to split override-able code into a separate method call:
public class Super
{
public final void doIt()
{
// cannot be overridden
doItSub();
}
protected void doItSub()
{
// override this
}
}
public class Sub extends Super
{
protected void doItSub()
{
// override logic
}
}
I stumbled on to this post and didn't necessarily like any particular answer, so I figured I would provide my own ...
There is no way in C# to enforce that the base method is called. Therefore coding as such is considered an anti-pattern since a follow-up developer may not realize they must call the base method else the class will be in an incomplete or bad state.
However, I have found circumstances where this type of functionality is required and can be fulfilled accordingly. Usually the derived class needs a resource of the base class. In order to get the resource, which normally might be exposed via a property, it is instead exposed via a method. The derived class has no choice but to call the method to get the resource, therefore ensuring that the base class method is executed.
The next logical question one might ask is why not put it in the constructor instead? The reason is that it may be an order of operations issue. At the time the class is constructed, there may be some inputs still missing.
Does this get away from the question? Yes and no. Yes, it does force the derived class to call a particular base class method. No, it does not do this with the override keyword. Could this be helpful to an individual looking for an answer to this post, maybe.
I'm not preaching this as gospel, and if individuals see a downside to this approach, I would love to hear about it.
On the Android platform there is a Java annotation called 'CallSuper' that enforces the calling of the base method at compile time (although this check is quite basic). Probably the same type of mechanism can be easily implemented in Java in the same exact way. https://developer.android.com/reference/androidx/annotation/CallSuper
Is it possible in C# to have a class that implement an interface that has 10 methods declared but implementing only 5 methods i.e defining only 5 methods of that interface??? Actually I have an interface that is implemented by 3 class and not all the methods are used by all the class so if I could exclude any method???
I have a need for this. It might sound as a bad design but it's not hopefully.
The thing is I have a collection of User Controls that needs to have common property and based on that only I am displaying them at run time. As it's dynamic I need to manage them for that I'm having Properties. Some Properties are needed by few class and not by all. And as the control increases this Properties might be increasing so as needed by one control I need to have in all without any use. just the dummy methods. For the same I thought if there is a way to avoid those methods in rest of the class it would be great. It sounds that there is no way other than having either the abstract class or dummy functions :-(
You can make it an abstract class and add the methods you don't want to implement as abstract methods.
In other words:
public interface IMyInterface
{
void SomeMethod();
void SomeOtherMethod();
}
public abstract class MyClass : IMyInterface
{
// Really implementing this
public void SomeMethod()
{
// ...
}
// Derived class must implement this
public abstract void SomeOtherMethod();
}
If these classes all need to be concrete, not abstract, then you'll have to throw a NotImplementedException/NotSupportedException from inside the methods. But a much better idea would be to split up the interface so that implementing classes don't have to do this.
Keep in mind that classes can implement multiple interfaces, so if some classes have some of the functionality but not all, then you want to have more granular interfaces:
public interface IFoo
{
void FooMethod();
}
public interface IBar()
{
void BarMethod();
}
public class SmallClass : IFoo
{
public void FooMethod() { ... }
}
public class BigClass : IFoo, IBar
{
public void FooMethod() { ... }
public void BarMethod() { ... }
}
This is probably the design you really should have.
Your breaking the use of interfaces. You should have for each common behaviour a seperate interface.
That is not possible. But what you can do is throw NotSupportedException or NotImplementedException for the methods you do not want to implement. Or you could use an abstract class instead of an interface. That way you could provide a default implementation for methods you choose not to override.
public interface IMyInterface
{
void Foo();
void Bar();
}
public class MyClass : IMyInterface
{
public void Foo()
{
Console.WriteLine("Foo");
}
public void Bar()
{
throw new NotSupportedException();
}
}
Or...
public abstract class MyBaseClass
{
public virtual void Foo()
{
Console.WriteLine("MyBaseClass.Foo");
}
public virtual void Bar()
{
throw new NotImplementedException();
}
}
public class MyClass : MyBaseClass
{
public override void Foo()
{
Console.WriteLine("MyClass.Foo");
}
}
While I agree with #PoweRoy, you probably need to break your interface up into smaller parts you can probably use explicit interfaces to provider a cleaner public API to your interface implementations.
Eg:
public interface IPet
{
void Scratch();
void Bark();
void Meow();
}
public class Cat : IPet
{
public void Scratch()
{
Console.WriteLine("Wreck furniture!");
}
public void Meow()
{
Console.WriteLine("Mew mew mew!");
}
void IPet.Bark()
{
throw NotSupportedException("Cats don't bark!");
}
}
public class Dog : IPet
{
public void Scratch()
{
Console.WriteLine("Wreck furniture!");
}
void IPet.Meow()
{
throw new NotSupportedException("Dogs don't meow!");
}
public void Bark()
{
Console.WriteLine("Woof! Woof!");
}
}
With the classes defined above:
var cat = new Cat();
cat.Scrach();
cat.Meow();
cat.Bark(); // Does not compile
var dog = new Dog();
dog.Scratch();
dog.Bark();
dog.Meow(); // Does not compile.
IPet pet = new Dog();
pet.Scratch();
pet.Bark();
pet.Meow(); // Compiles but throws a NotSupportedException at runtime.
// Note that the following also compiles but will
// throw NotSupportedException at runtime.
((IPet)cat).Bark();
((IPet)dog).Meow();
You can simply have the methods you don't want to impliment trow a 'NotImplementedException'. That way you can still impliment the interface as normal.
No, it isn't. You have to define all methods of the interface, but you are allowed to define them as abstract and leave the implementation to any derived class. You can't compile a class that says that implements an interface when in fact it doesn't.
Here is a simple stupid example of what I meant by different interfaces for different purposes. There is no interface for common properties as it would complicate example. Also this code lacks of many other good stuff (like suspend layout) to make it more clear. I haven't tried to compile this code so there might be a lot of typos but I hope that idea is clear.
interface IConfigurableVisibilityControl
{
//check box that controls whether current control is visible
CheckBox VisibleCheckBox {get;}
}
class MySuperDuperUserControl : UserControl, IConfigurableVisibilityControl
{
private readonly CheckBox _visibleCheckBox = new CheckBox();
public CheckBox VisibleCheckBox
{
get { return _visibleCheckBox; }
}
//other important stuff
}
//somewhere else
void BuildSomeUi(Form f, ICollection<UserControl> controls)
{
//Add "configuration" controls to special panel somewhere on the form
Panel configurationPanel = new Panel();
Panel mainPanel = new Panel();
//do some other lay out stuff
f.Add(configurationPanel);
f.Add(mainPanel);
foreach(UserControl c in controls)
{
//check whether control is configurable
IConfigurableOptionalControl configurableControl = c as IConfigurableVisibilityControl;
if(null != configurableControl)
{
CheckBox visibleConfigCB = configurableControl.VisibleCheckBox;
//do some other lay out stuff
configurationPanel.Add(visibleConfigCB);
}
//do some other lay out stuff
mainPanel.Add(c);
}
}
Let your Interface be implemented in an abstract class. The abstract class will implement 5 methods and keep remaining methods as virtual. All your 3 classes then should inherit from the abstract class. This was your client-code that uses 3 classes won't have to change.
I want to add dynamically the control to my form as I have that as my requirement. I found the code from here. I edited it as I needed. So I have the IService class that has the common properties. This is implemented by the User Controls. Which are shown at runtime in different project. Hmmm for that I have different common interface that has properties which are used by the project for displaying the controls. Few controls need some extra methods or peoperties for instance to implement a context menu based on user selection at runtime. i.e the values are there in the project which will be passed as the properties to the control and it will be displayed. Now this menu is there only for one control rest of them don't have this. So I thought if there is a way to not to have those methods in all class rather than one class. But it sounds that I need to either go for dummy methods or abstract class. hmmm dummy methods would be more preferable to me than the abstract class :-(
By implementing one of the SOLID principle which is "Interface Segregation Principle" in which Interface is broken into mutiple interfaces.
Apart from the above excellent suggestions on designing interfaces, if you really need to have implementation of some of the methods,an option is to use 'Extension methods'. Move the methods that need implementation outside of your interface. Create another static class that implements these as static methods with the first parameter as 'this interfaceObject'. This is similar to extension methods used in LINQ for IEnumerable interface.
public static class myExtension {
public static void myMethod( this ImyInterface obj, ... ) { .. }
...
}