A way to extend existing class without creating new class in c# - c#

I have a good complete class which is doing awesome things. I need to allow users to use this class by replacing some methods in it, but inheritance is not allowed, because this class also used in other application classes.
It is like you have a class which creating a table, but you need to allow users to redefine method which is creating table cell to let the user print something custom in this cell. The class, however, has a default way to print the cell content (in case the user do not need to customize it).
Is there any common-used or standartized way to achieve this?

Updated
Having had "the peanut gallery" point out that my approach (at bottom) wouldn't fit the bill, here's another way:
Use delegation. Define certain public properties with type Action or Func. Where these behaviors need to be invoked in your code, compare the properties to null. If null, use your default behavior. If not, invoke the values.
Your calling code MAY set the properties, but doesn't have to.
(first try) Alternative approaches:
You are describing an extension method, or the use of inheritance if that's available.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
https://msdn.microsoft.com/en-us//library/bb383977.aspx
Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics (or pillars) of object-oriented programming. Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB, and ClassB is derived from ClassA, ClassC inherits the members declared in ClassB and ClassA.
https://msdn.microsoft.com/en-us/library/ms173149.aspx
You can't derive from all .NET types, but you can write extension methods for them.

Assuming you are able to modify the existing class, you should be marking your method as virtual.
This will allow you to provide a default implementation (which is what your existing code will use) and be able to override it with a custom one where needed.
Your base class could be something along the lines of:
public class TableMaker
{
public virtual string MakeTable()
{
//Provide default implementation used by existing code here
}
}
Your inheriting class can then override the virtual method:
public class SpecialTableMaker : TableMaker
{
public override string MakeTable()
{
//Provide specific implementation for cell text here
}
}
You existing code will work just fine and you can use this other class where you need it.

I've finally ended with this solution. It was proposed by #codenoir, however I also have a code which demonstrates a whole mechanism.
public class MyTable
{
public delegate string OnInsertHandler();
public event OnInsertHandler OnInsert;
public string Show()
{
string res = "-BEGIN-";
if (OnInsert != null) {
res += OnInsert ();
} else {
res += "#default insert#";
}
res += "-END-";
return res;
}
}
public class DelegateTester
{
public void OnTest()
{
MyTable mt = new MyTable();
Debug.Log("Default output: " + mt.Show()); // Shows "-BEGIN-#default insert#-END-"
// Changing functionality via delegate
mt.OnInsert += MyCustomInsert;
Debug.Log("Customized output: " + mt.Show()); // Shows "-BEGIN-#custom insert#-END-"
// Remove delegate
mt.OnInsert -= MyCustomInsert;
Debug.Log("Rollbacked output: " + mt.Show()); // Shows "-BEGIN-#default insert#-END-"
}
public string MyCustomInsert()
{
return "#custom insert#";
}
}
In this example I am using MyTable class which is extended using Func delegate. This way I can allow to users of my software module to extend only one method without make any mess with others classes and objects.

Related

How can I add another argument to CompareTo method?

How can I add another argument to the CompareTo method so I can implement a switch statement to allow my program to select what the CompareTo method will be comparing?
Current I'm doing:
public int CompareTo(Employee other)
{
return name.CompareTo(other.name);
}
What I want to do:
public int CompareTo(Employee other, string choice)
{
switch(choice)
{
case "name":
return name.CompareTo(other.name);
case "number"
return number.CompareTo(other.number);
}
return name.CompareTo(other.name);
}
I assume you're asking how you can extend the functionality of existing classes that you can't modify (otherwise you could directly edit the class itself), and if that's the case, I'd recommend making an extension method as such:
public static class EmployeeExtensions {
public static int CompareTo(this Employee baseEmployee, Employee other, string choice){
... code ....
return 0;
}
}
This will then allow you to extend the compare to functionality, and call this from wherever you require it. You need to put the extension method in its own static class.
You can call it by going:
Employee a = new Employee(...);
Employee b = new Employee(...);
a.CompareTo(b, "args");
Assuming the extension class has been imported where you are trying to use it. This is usually the way C# allows for extending functionality of classes you do not have access to. Although if you do have access to the class I'd recommend editing the class itself and making a new method (you may be able to override, but if they provide distinct functionality you'll need to write two methods, in this case code duplication is ok).
This doesn't apply if you're actually trying to change the default equality members, and if that's the case, you can't add your own argument and have it still work with existing infrastructure such as list sorting, so I'd recommend re-evaluating your problem if you 'want to add an argument to equals' for example.
If you're trying to change the way objects compare (objects implementing IComparable), then make your own IComparer, and use that to do the comparing, don't try and change the way CompareTo is done on the class, as the default behavior of Compare (with arguments as is) is useful. I'm also not saying don't implement IComparable (rather than making a IComparer) if it makes sense and you have access to the class then use an IComparable, but that won't allow you to change the arguments of the inherited compare method.

Hook to object instantiation

I'm wondering if there's a way to hook to an event whenever an object is instantiated.
If it doesn't, is there a way to retrieve the object to which an attribute is attached to when the attribute is instantiated?
What I want to do is give some of my classes a custom attribute and whenever a class with this attribute is instantiated, run some code for it.
Of course, I could simply place the code in each of those classes' constructor but that's a lot of copy and pasting and I could easily forget to copy that code into one or two classes. And of course, would be very convenient for end users as all they would have to do is add my attribute to their classes and not worry about remember to add that bit of code in their constructors.
I actually can't do a base class because all of those objects already have a base.
Thanks in advance.
Here's an example of what I'd like to do. Either use the attribute's constructor or have an event handler for object instantiation.
public class MySuperAttribute : Attribute
{
public MySuperAttribute()
{
//Something akin to this or the event in Global
Global.AddToList(this.TheTargetObject);
}
}
[MySuperAttribute]
public class MyLabel : System.Windows.Forms.Label
{
}
public static class Global
{
public static void AddToList(Object obj)
{
//Add the object to a list
}
//Some pseudo-hook into the instantiation of any object from the assembly
private void Assembly_ObjectInstantiated(Object obj)
{
if(obj.GetType().GetCustomAttributes(typeof(MySuperAttribute), true).Count != 0)
AddtoList(obj);
}
}
There is no easy way to hook object instantiation externally, maybe with some debugging API, and it has a good reason. It makes your code harder to maintain and understand for other people.
Attributes won't work, because the instance of an attribute is not actually created until it is required - via reflection, and an attribute is assigned to a type, not an instance.
But you may well put the code in a base class, and derive all other classes from it, although it is also not a good practice to pass half-initialized instance to other methods. If the class inherits from ContextBoundObject, you can assign a custom implementation of ProxyAttribute to it and override all operations on it.
If you can't create a common base class (when your types inherit from different types), you can always create the instance with a custom method like this one:
public static T Create<T>() where T : new()
{
var inst = new T();
Global.AddToList(inst);
return inst;
}
However, seeing as you inherit from form controls, their instantiation is probably controlled by the designer. I am afraid there is no perfect solution, in this case.

The use of C# extension methods to show intention

Say I have a class, A, which holds some state:
class A
{
// Ctor etc.
string Foo { get; private set; }
string Bar { get; private set; }
}
This class is used thoughout my codebase to hold application state. Ultimately, this state gets written into an XML file to save it. Naturally, I'll write a method to do just that:
class A
{
// Ctor, the state, etc.
public string ToXml()
{
// Writer implementation goes here
return xmlString;
}
}
ToXml does not require access to any of A's private/protected instance variables, it only uses uses A's public interface. Since that's the case, I can implement ToXml as an extension method:
class A
{
// Ctor, the state, etc.
public static string ToXml(this A instance)
{
// Same deal as above
return xmlString;
}
}
An extension method can only use the outer interface of the class it is extending. So, ignoring extension methods' main uses (extending a locked class, semantic helpers), what's the SO community's opinion on using an extension method for the sole purpose of communicating that a method only uses the outer interface of a class?
I ask this because I personally use extension methods alot--perhaps because I enjoy functional programming--but my coworkers dislike the rationale that I do so because I want to communicate that "this particular method definitely only uses the public interface of the class".
Note: These extension methods will appear as a substitute for their instance equivalents. Because of that, there will not be any of the usual namespace issues that occur with extension methods. This question focuses entirely on the "communicate intent" aspect.
Extension methods are an example of the Open/Closed Principle. That is, it's open for extension, but closed for modification.
The major benefit of using Extension methods is that you do not have to recompile the class that is being extended, and thus force dependent code to be recompiled. Also, by not changing the interface, you don't have to worry about any code depending on it breaking.
If you're serious about SOLID principles, then this is a valid argument. Most developers don't see what the fuss is about.
You have a class, A, that has a specific responsibility: holding a set of immutable data. If you now add a new method, ToXml, your class no longer has a specific responsibility; it has two loosely related responsibilities: holding data and translating that data into another form.
So to preserve the single responsibility principle, such lossely related functionality should exist in another class, eg DataTransformationsOnA. As the method is a pure function (it creates a deterministic output from an input with no side affects, it should be made a static method. Therefore, it follows that it can be made an extension method:
static class DataTransformationsOnA
{
public static string ToXml(this A instance)
{
// generate xmlSTring from instance
return xmlString;
}
// other transformation methods can also be placed in this class
}

How to *easily* expose methods of underlying objects?

Let's say I have some classes defined as follows:
class Security
{
Boolean AuthenticateUser(String username, String password);
Boolean AddUser(String username, String password);
// many more methods
}
class NetworkedDevice
{
void Stop();
void Start();
// many more methods
}
Then I have another class that contains instances of the above classes. How can I avoid code like the following? I want all the methods of class1 and class2 exposed via this class.
class MyWindowsService
{
Security _security = new Security();
NetworkDevice _netDevice = new NetworkDevice();
Boolean AuthenticateUser(String username, String password)
{
return _security.AuthenticateUser(username, password);
}
// all the rest of "Security" methods implemented here
void StopNetworkDevice()
{
_netDevice.Stop();
}
void StartNetorkDevice()
{
_netDevice.Start();
}
// all the rest of "NetDevice" methods implemented here
}
Edit
I've updated the code to be more real to what I am doing. I am hosting a WCF service within a windows service. The windows service does several things including user authentication and communication to networked devices to name a few. The implementation of my WCF interface calls methods of the "MyWindowsService" class. Exposing the underlying objects as properties is the answer I was looking for. The above class then looks something like:
class MyWindowsService
{
SecurityClass _security = new SecurityClass();
NetworkDevice _netDevice = new NetworkDevice();
Public NetworkDevice NetDevice
{
get { return _netDevice; }
}
Public SecurityClass Security
{
get { return _security; }
}
}
Well, if you're using composition (as you are) there is no "easier way"; you just have to wrap the methods you want to expose. If you want to expose all of the methods of the composed type, then why are you using composition in the first place? You may as well just expose SecurityClass and NetworkDevice via public properties as it is functionally no different than wrapping every method and property/public field.
If it makes sense that they belong in the inheritance chain then SuperClass (oddly named as it would be a sub class...) should inherit from one of those classes. Of course you can't inherit from both in C#, but this design makes me suspect that there may be a better overall approach. It is impossible to tell from your code sample though as you don't tell us what you are actually trying to accomplish with these types.
There is one more way: T4 Templates.
See here: http://msdn.microsoft.com/en-us/data/gg558520
The resulting CS file is generated at build time. This means you could potentially loop your classes using refelection and the result would be what you have now manually created in your "SuperClass".
The cool thing really is that the resulting code is generated on the fly and it is typesafe.
Is it worth the effort? I don't know. It really depends what you are doing and why you are doing it.
We use it for instance to translate Func<T1, T2> into "real" delegates and auto-generate wrapper classes that way.
Unfortunately there is no magic ways to do that as multiple type inheritance is not allowed in .NET.
You cannot do this easily in C#. You could inherit from one of the classes, and create delegates for the other, or you can manually create delegates for both (by delegate, I just mean a method that delegates to the member object, not anything to do with the delegate keyword or class).
If you use a product such a Resharper, there is an option in the Refactor menu that will automate this process, called "Create delegates..."
You can make class1 public and then reference them directly:
SuperClass.class1.MethodFirst();
Of course, static methods will be ok, you will have to construct class1 for instance methods.
in C#, you cannot combine class hierarchies the way you can in Java but you can enforce a contract through iterfaces.
Create an interface for Class1 and Class2 then have SuperClass implement those interfaces. You'll still code up the method calls, but at least you'll have some compile-time checking in place. Perhaps you could also Create a method in SuperClass that dispatches to the appropriate class/method using reflection.
Another approach might be to setup an inheritance chain where SuperClass extends Class2 which extends Class1.
The question is rather old already, and there's one more solution available today: Expose.Fody. This is a plugin for Fody, which is a general-purpose IL-weaving tool. To quote the Expose's description,
Exposes members and optionally implements interface of a field declared in class.
All it takes is just decorating the field with an attribute.

How to handle static fields that vary by implementing class

I hit this problem all the time. Suppose I am making a command line interface (Java or C#, the problem is the same I think, I will show C# here).
I define an interface ICommand
I create an abstract base class CommandBase which implements ICommand, to contain common code.
I create several implementation classes, each extending the base class (and by extension the interface).
Now - suppose that the interface specifies that all commands implement the Name property and the Execute method...
For Name each of my instance classes must return a string that is the name of that command. That string ("HELP", "PRINT" etc) is static to the class concerned. What I would love to be able to do is define:
public abstract static const string Name;
However (sadly) you cannot define static members in an interface.
I have struggled with this issue for years now (pretty much any place I have a family of similar classes) and so will post my own 3 possible solutions below for your votes. However since none of them is ideal I am hoping someone will post a more elegant solution.
UPDATE:
I can't get the code formatting to work properly (Safari/Mac?). Apologies.
The example I am using is trivial. In real life there are sometimes dozens of implementing classes and several fields of this semi-static type (ie static to the implementing class).
I forgot to mention - ideally I want to be able to query this information statically:
string name = CommandHelp.Name;
2 of my 3 proposed solutions require that the class be instantiated before you can find out this static information which is ugly.
You may consider to use attributes instead of fields.
[Command("HELP")]
class HelpCommand : ICommand
{
}
As you mentioned, there is no way to enforce this from the interface level. Since you are using an abstract class, however, what you can do is declare the property as abstract in the base class which will force the inheriting class it override it. In C#, that would look like this:
public abstract class MyBaseClass
{
public abstract string Name { get; protected set; }
}
public class MyClass : MyBaseClass
{
public override string Name
{
get { return "CommandName"; }
protected set { }
}
}
(Note that the protected set prevents outside code changing the name.)
This may not be exactly what you're looking for, but it's as close as I think you can get. By definition, static fields do not vary; you simply can't have a member that is both static and overridable for a given class.
public interface ICommand {
String getName();
}
public class RealCommand implements ICommand {
public String getName() {
return "name";
}
}
Simple as that. Why bother having a static field?
Obs.: Do not use a field in an abstract class that should be initiated in a subclass (like David B suggestion). What if someone extends the abstract class and forget to initiate the field?
just add the name property to the base class and pass it ito the base class's constructor and have the constuctor from the derived class pass in it's command name
What I usually do (in pseudo):
abstract class:
private const string nameConstant = "ABSTRACT";
public string Name
{
get {return this.GetName();}
}
protected virtual string GetName()
{
return MyAbstractClass.nameConstant;
}
----
class ChildClass : MyAbstractClass
{
private const string nameConstant = "ChildClass";
protected override string GetName()
{
return ChildClass.nameConstant;
}
}
Of course, if this is a library that other developers will use, it wouldn't hurt if you add some reflection in the property to verify that the current instance in fact does implement the override or throw an exception "Not Implemented".
My answer will relate to Java, as that is what I know. Interfaces describe behavior, and not implementation. Additionally, static fields are tied to the classes, and not instances. If you declared the following:
interface A { abstract static NAME }
class B { NAME = "HELP" }
class C { NAME = "PRINT" }
Then how could this code know which NAME to link to:
void test(A a) {
a.NAME;
}
How I would suggest to implement this, is one of the following ways:
Class name convention, and the base class derives the name from the class name. If you wish to deviate from this, override the interface directly.
The base class has a constructor which takes name
Use annotations and enforce their presence through the base class.
However, a much better solution is proabably to use enums:
public enum Command {
HELP { execute() }, PRINT { execute() };
abstract void execute();
}
This is much cleaner, and allows you to use switch statements, and the NAME will be easily derived. You are however not able to extended the number of options runtime, but from your scenario description that might not be even needed.
[Suggested answer # 3 of 3]
I have not tried this yet and it would not be so nice in Java (I think?) but I could just tag my classes with Attributes:
[CammandAttribute(Name="HELP")]
Then I can use reflection to get that static information. Would need some simple helper methods to make the information easily available to the clients of the class but this could go in the base class.
From a design perspective, I think it is wrong to require a static implementation member... The relative deference between performance and memory usage between static and not for the example string is minimal. That aside, I understand that in implementation the object in question could have a significantly larger foot print...
The essential problem is that by trying to setup a model to support static implementation members that are avaialble at a base or interface level with C# is that our options are limited... Only properties and methods are available at the interface level.
The next design challenge is whether the code will be base or implementation specific. With implementation your model will get some valdiation at compile time at the code of having to include similar logic in all implementations. With base your valdiation will occur at run time but logic would be centralized in one place. Unfortunately, the given example is the perfect show case for implemntation specific code as there is no logic associated with the data.
So for sake of the example, lets assume there is some actual logic associated with the data and that it is extensive nad/or complex enough to provide a showcase for base classing. Setting aside whether the base class logic uses any impelementation details or not, we have the problem of insuring implemtation static initialization. I would recommend using an protected abstract in the base class to force all implementations to created the needed static data that would be valdated at compile time. All IDE's I work with make this very quick any easy. For Visual Studio it only takes a few mouse clicks and then just changing the return value essentially.
Circling back to the very specific nature of the question and ignoring many of the other design problems... If you really must keep this entire to the nature of static data and still enforce it thru the nature confines of the problem... Definately go with a method over properties, as there are way to many side effects to make go use of properties. Use a static member on the base class and use a static constructor on the implementations to set the name. Now keep in mind that you have to valdiate the name at run-time and not compile time. Basically the GetName method on the base class needs to handle what happens when an implementation does not set it's name. It could throw an exception making it brutally apparent that something is worng with an implementation that was hopefulyl cause by testing/QA and not a user. Or you could use reflection to get the implementation name and try to generate a name... The problem with reflection is that it could effect sub classes and set up a code situation that would be difficult for a junior level developer to understand and maintain...
For that matter you could always generate the name from the class name thru reflection... Though in the long term this could be a nightmare to maintain... It would however reduce the amount of code needed on the implementations, which seems more important than any other concerns. Your could also use attributes here as well, but then you are adding code into the implementations that is equivalent in time/effort as a static constructor and still have the problem off what todo when the implementation does not include that information.
What about something like this:
abstract class Command {
abstract CommandInfo getInfo();
}
class CommandInfo {
string Name;
string Description;
Foo Bar;
}
class RunCommand {
static CommandInfo Info = new CommandInfo() { Name = "Run", Foo = new Foo(42) };
override commandInfo getInfo() { return Info; }
}
Now you can access the information statically:
RunCommand.Info.Name;
And from you base class:
getInfo().Name;
[Suggested solution #1 of 3]
Define an abstract property Name in the interface to force all implementing classes to implement the name property.
(in c#) Add this property as abstract in the base class.
In the implementations implement like this:
public string Name
{
get {return COMMAND_NAME;}
}
Where name is a constant defined in that class.
Advantages:
Name itself defined as a constant.
Interface mandates the property be created.
Disadvantages:
Duplication (which I hate). The exact same property accessor code pasted into every one of my implementations. Why cant that go in the base class to avoid the clutter?
[Suggested solution #2 of 3]
Make a private member variable name.
Define an abstract property Name in the interface.
Implement the property in the base class like this:
public string Name
{
get {return Name;}
}
Force all implementations to pass name as a constructor argument when calling the abstract base class constructor:
public abstract class CommandBase(string commandName) : ICommand
{
name = commandName;
}
Now all my implementations set the name in the constructor:
public class CommandHelp : CommandBase(COMMAND_NAME) {}
Advantages:
My accessor code is centralised in the base class.
The name is defined as a constant
Disadvantages
Name is now an instance variable -
every instance of my Command classes
makes a new reference rather than
sharing a static variable.

Categories