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()
Related
What is the difference between a Facade and a Template method pattern? Both of them provide high level views of the subsystem and hide it from the user.
Facade Pattern
internal class SubsystemA
{
internal string A1()
{
return "Subsystem A, Method A1\n";
}
internal string A2()
{
return "Subsystem A, Method A2\n";
}
}
internal class SubsystemB
{
internal string B1()
{
return "Subsystem B, Method B1\n";
}
}
internal class SubsystemC
{
internal string C1()
{
return "Subsystem C, Method C1\n";
}
}
public static class Facade
{
static SubsystemA a = new SubsystemA();
static SubsystemB b = new SubsystemB();
static SubsystemC c = new SubsystemC();
public static void Operation1()
{
Console.WriteLine("Operation 1\n" +
a.A1() +
a.A2() +
b.B1());
}
public static void Operation2()
{
Console.WriteLine("Operation 2\n" +
b.B1() +
c.C1());
}
}
// ============= Different compilation
// Compile with csc /r:FacadeLib.dll Facade-Main.cs
class Client
{
static void Main()
{
Facade.Operation1();
Facade.Operation2();
}
}
Template pattern
interface IPrimitives
{
string Operation1();
string Operation2();
}
class Algorithm
{
public void TemplateMethod(IPrimitives a)
{
string s =
a.Operation1() +
a.Operation2();
Console.WriteLine(s);
}
}
class ClassA : IPrimitives
{
public string Operation1()
{
return "ClassA:Op1 ";
}
public string Operation2()
{
return "ClassA:Op2 ";
}
}
class ClassB : IPrimitives
{
public string Operation1()
{
return "ClassB:Op1 ";
}
public string Operation2()
{
return "ClassB.Op2 ";
}
}
class TemplateMethodPattern
{
static void Main()
{
Algorithm m = new Algorithm();
m.TemplateMethod(new ClassA());
m.TemplateMethod(new ClassB());
}
}
This example has been taken from O'Reilly Design Patterns
In the above provided example, both Facade and Template pattern Implement an interface and the uses an abstraction and defines on how the operation should be handled. I dont find any difference between the two patterns. Can anyone help me understand it.
Facade pattern will introduce new functionality by combining sub functionalities under wrapper method.
Facade class in this case have different structure then sub classes.
Template pattern provide skeleton of algorithm in the base class and gives possibility for derived classes to override/implement some units of this algorithm.
In this case classes derived from template have same structure as base class.
The main purpose of the template method pattern is to define some generic algorithm, where some implementation details might be specified by the derived classes.
Here is an example:
abstract class Car
{
public void Drive()
{
IgnitionOn();
EngineOn();
EngageTransmission();
}
protected abstract void IgnitionOn();
protected abstract void EngineOn();
protected abstract void EngageTransmission();
}
Here the Drive() method is a template method that defines the generic behavior (how to drive). But every derived class can (or, in this example, have to) provide implementation details.
Example:
class DieselCarWithManualGearbox : Car
{
protected override void IgnitionOn()
{
IgnitionControlModule.IgnitionState = IgnitionState.On;
}
protected override void EngineOn()
{
DieselEngine.StartFuelPump();
DieselEngine.Run();
}
protected override void EngageTransmission()
{
ManualGearbox.Gear = 1;
}
}
The DieselCarWithManualGearbox class provides some specific implementation, but the whole algorithm stays unchanged. Then you create some ElectroCarWithAutomaticGearbox that uses the same algorithm for driving, but needs its own ElectricEngine and AutomaticGearbox stuff to do it properly.
The facade pattern can be used to simplify the usage of some logic that is contained in multiple interfaces or modules. For example, the static class Console can be seen as a facade for console usage. It hides the implementation details and provides a couple of simple methods we can easily use. We cannot change the behavior of a facade though by providing some additional implementatons. That is the difference.
In simple words: The template method belongs to a base class and allows the subclasses to redefine some steps. You create an object of a class and invoke this template method to complete your job.
But facades often involve multiple objects from many different classes. This time you perform a series of steps to accomplish the task involving all these objects. You do not redefine the methods in these classes, instead, you manage to call them easily.
Now to aswer your question:
In your example, in the template pattern, see that you use only one object of the Algorithm. But it is not the case for a facade. Though you have used static objects, see how many different types of objects are involved there.
I want a particular method in one class to only be accessible by a particular class. For example:
public class A
{
public void LimitedAccess() {}
public void FullAccess() {}
}
public class B
{
public void Func()
{
A a = new A();
a.LimitedAccess(); // want to be able to call this only from class B
}
}
public class C
{
public void Func()
{
A a = new A();
a.FullAccess(); // want to be able to call this method
a.LimitedAccess(); // but want this to fail compile
}
}
Is there is a keyword or attribute that I can use to enforce this?
UPDATE:
Due to existing system complexity and time constraints, I needed a low impact solution. And I wanted something to indicate at compile time that LimitedAccess() could not be used. I trust Jon Skeet's answer that exactly what I had asked for could not be done in C#.
The question and Jon's answer are good for those who may run across this later. And the fact that this design smells can hopefully veer anyone away for choosing something like this as a desired a solution.
As mentioned in a comment, the C# friend conversation is useful reading if you are trying to solve a similar situation.
As for my particular solution: "why would A contain B's logic" (asked by #sysexpand in comments). That's the rub. B.Func() was called throughout the system I'm working on, but it primarily operated on a singleton of A. So what I ended up doing was moving B's Func() into A and making A.LimitedAccess() private. There were a few other details to work around, as there always are, but I got a low impact solution that gave me compile-time errors on callers to A.LimitedAccess().
Thanks for the discussion.
No. The only thing you could do would be to make LimitedAccess a private method, and nest class B within class A.
(I'm assuming you want all the classes in the same assembly. Otherwise you could put A and B in the same assembly, and C in a different assembly, and make LimitedAccess an internal method.)
Yes. What you are asking for is perfectly possible.
You can restrict access to methods and variables for a specific instance, by using an interface.
However, an interface alone cannot prevent someone from creating their own instance of the class, at which point they will have full access to that instance.
To do that, next you should nest it as a private class inside of another class in order to restrict access to the constructor.
Now you have a particular method in one class to only be accessible by a particular class.
In this example, only class B is ever able to access function LimitedAccess.
public interface IA
{
void FullAccess();
}
public class B
{
private class A : IA
{
public void LimitedAccess() {} //does not implement any interface
public void FullAccess() {} //implements interface
}
private A a = new A();
public IA GetA()
{
return (IA)a;
}
public void Func()
{
/* will be able to call LimitedAccess only from class B,
as long as everybody else only has a reference to the interface (IA). */
a.LimitedAccess();
}
}
//This represents all other classes
public class C
{
public void Func(IA ia)
{
ia.FullAccess(); // will be able to call this method
ia.LimitedAccess(); // this will fail to compile
}
}
public static class MainClass
{
public static void Main(string[] args)
{
B b = new B();
b.Func();
IA ia = b.GetA();
C c = new C();
c.Func(ia);
}
}
In case you just want to remind yourself (or team mates) to not call LimitedAccess everywhere, you could consider using explicit interface implementation or mark LimitedAccess as obsolete.
public interface IA
{
void LimitedAccess();
void FullAccess();
}
public class A : IA
{
private void LimitedAccess() { }
public void FullAccess() { }
void IA.LimitedAccess() => LimitedAccess();
void IA.FullAccess() => FullAccess();
}
public class B
{
public void Func()
{
IA a = new A();
a.LimitedAccess(); // want to be able to call this only from class B
}
}
public class C
{
public void Func()
{
A a = new A();
a.FullAccess(); // want to be able to call this method
a.LimitedAccess(); // -> fails to compile
}
}
Maybe this is a workaround.
Use the System.Runtime.CompilerServices and then you can either check the Name of the calling function and/or the file, in which the calling function is defined. If you have a class per file, the filename might be a substitude for the class name. Check it and block the call.
internal void MySecretFunction (string something,
[CallerMemberName] string memberName = null,
[CallerFilePath] string filePath = null,
[CallerLineNumber] int lineNumber = 0) {
if (!filePath.EndsWith(#"\goodClass.cs")) return;
// else do something
}
You could always see the calling type with a StackTrace.
Just note that when building in release mode, the call on the stack will get optimized, and its possible that the stack trace could return a completely different class, so just make sure to test it before you publish.
/// <summary>
/// Warning: Any class that calls this other than "B" will throw an exception.
/// </summary>
public void LimitedAccess()
{
if (new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().DeclaringType != typeof(B)) throw new Exception("Invalid Caller Type, B is only class able to call this method.");
}
Unfortunately you wont be able to know if its an error on compile time. Best you can do is throw an exception if it gets called, and add a comment warning people about it.
It is against OOP best practices to make such a design. Methods of classes are not supposed to be protected from being called.
If your design requires control over calling a method, then control should be exercised by testing the arguments - caller which is authorized to make a call would "know" the magic word to pass as the argument.
This is a variation of the solution suggested by #cowlinator using class AWithUnlimitedAccess derived from class A rather than class A implementing interface IA.
The result and the limitations are the same, but I like it better because (1) the limited access methods are defined inside its own class and (2) it's easier to add documentation comments.
public class A
{
public void FullAccess() { }
}
public class AWithUnlimitedAccess : A
{
public void LimitedAccess() { }
}
public class B
{
private AWithUnlimitedAccess a = new AWithUnlimitedAccess();
public A GetA()
{
return a;
}
public void Func()
{
a.FullAccess();
a.LimitedAccess();
}
}
// This represents all other classes
public class C
{
public A A;
public void Func()
{
A.FullAccess();
A.LimitedAccess(); // this will fail compile
}
}
public static class MainClass
{
static void Main(string[] args)
{
B b = new B();
b.Func();
C c = new C();
c.A = b.GetA();
c.Func();
}
}
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 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, ... ) { .. }
...
}
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.