C# .net - override existing built-in function + get underlying method code - c#

Apologies if these are extremely basic questions, but let's say I'm using the void Add(T item) function of BlockingCollection:
1) How would I override the Add function, i.e. if I want to add a check at the beginning and then call the base function, is this possible to do, and if so, would the code look something like this?
protected sealed class BlockingCollection<T> : IEnumerable<T>
{
protected override void Add(T item)
{
// do something here
// call base blockingcollection add function, something like return base.Add(item)??
}
}
2) If instead of calling the base function, I wanted to actually modify the Add code, is there a way to get the underlying code for the Add function? Would I use something such as Reflection? If so, is there any way to get the underlying code without writing my own program and using reflection to get the method code (i.e. can I get the underlying method code within the Visual Studio IDE itself without having to write / compile / run code every time I want to get the underlying code of a method?)?

IEnumerable doesn't have an "Add" method; you'd have to implement your own. ICollection does, however!
Also, because IEnumerable/ICollection are interfaces, not classes, there's no existing implmementation for you to override. You have to do that part yourself.
Edit for possible additional extra super duper correctness:
If you're trying to subclass BlockingCollection and you want to do some additional "stuff" before T is added via "Add", you could do it like this:
public class Foo<T> : BlockingCollection<T>
{
public new void Add(T item)
{
base.Add(item);
base.Add(item);
}
}
So, this extremely simple implementation will add anything you put into your Foo via "Add" twice.

I hope you are aware that you are creating a brand new BlockingCollection class, you aren't modifying the System.Collections.Concurrent.BlockingCollection<T> class that's part of the BCL.
Actually modifying the library version of BlockingCollection<T>.Add would be quite difficult to say the least. It's distributed as a signed binary, and .NET doesn't provide a detours-style mechanism. Although DynamicMethod allows you to add new methods to existing classes, I don't think you can use it to replace existing methods.

1) Yes, that is the correct way to do what you are asking.
2) You use a decompiler to view source code for a library API you are choosing to override. This is done by you, the human, and not as part of program execution.
Reflection is a bit different. It allows your code to access an API at run time, but does not access nor expose the API's source code. There are a lot of resources out there, but you could start on MSDN.
Update:
Since the method you are overriding is void, you may not change the implementation by returning something. Try this:
protected override void Add(T item)
{
// do something here
// call base blockingcollection add function
base.Add(item);
// this is unnecessary, but you could do it for giggles
return;
}

If the original library has allowed you to override Add then the pseudo-code you show is along the right track. You do need a bit of modification though if I understand your question properly.
First, you would create your own class, inheriting the old class and if not already done by the old class implementing the IEnumerable interface. Of course if the old class is "sealed" you will not be able to do this.
protected sealed class MyBlockingCollection<T> : BlockingCollection<T>, IEnumerable<T>
{
protected override void Add<T>(T item)
{
}
}
now marking your class as sealed will prevent anyone from further overriding methods exposed. If the old class is marked sealed, you will not be able to do this.
To see the code, you will need to decompile the library, using a tool which could be easy or difficult depending on the level of obfuscation that may or may not be employed to keep you from doing just that.
Edit: just winging the code, you should check a reference to ensure you have the appropriate syntax for what you are trying to do.

Related

How do I override a virtual method without changing the behaviour?

When you override a method, you shouldn't change the behaviour of the method, you just specialise it. Therefore you have to call base.MyVirtualMethod() in the overridden method and add the specialisation code.
But I'm always wondering when I have to call the base.MyVirtualMethod(). Or from another point of view, how do I write my virtual method? Should I expect the user will call it as the first or the last thing the overridden method does?
public class Parent
{
public virtual void MyMethod(){ /* Some code*/ }
}
public class Child : Parent
{
public override void MyMethod()
{
/* Does my code goes here? */
base.MyMethod();
/* Or does my code goes here? */
}
}
Therefore you have to call base.MyVirtualMethod() in the overridden
method and add the specialisation code.
That is not always true - there are cases when you don't want to do in the derived class what the superclass is doing so you don't want to call base.
If you want to extent the base behavior you place your code before or after base call, depending on the actual problem. There is no rule 'always call base before your code'.
The base call does not have to be present. You can specify in the documentation whether the base call should be before other code, after other code, both, or neither (absent), and exactly what the nature of the other code should be. This will all depend on what you are trying to accomplish.
If you find that the best place for the additional code would really be somewhere inside the base call, then that means the base method should be split into two or more methods.
The answer is, as with many questions, "It depends".
Assume that you're extending class which writes some data to a file, and the extension needs to add more data at the end of the file (SimpleDataFile.writeFile() extended by ExtendedDataFile.writeFile()): in such a scenario, you would add your code after the call to the base method.
Now, assume your extension adds a pre-processing facility, maybe adding color to the base file output (SimpleDataFile.writeFile() extended by FancyDataFile.writeFile()): in such a scenario you would realistically act before anything is sent to the file, and your code would end up before the base call.
To answer your question accurately: don't override it :) When you override it, you will change the behaviour.
Most of the times I put new code below the calling of the base method, since it does perform this base behaviour and then some more additional behaviour. However this is not set in stone, and really depends on your needs.
I generally call the base method first to assure that any required initialization has already happened and that my code actually overrides the base behavior, instead of the other way around.
Obviously this depends on the specific situation though, there may very well be occasions where you know your code needs to run first.
It depends on what you wanna do but both are OK !

C# has abstract classes and interfaces, should it also have "mixins"?

Every so often, I run into a case where I want a collection of classes all to possess similar logic. For example, maybe I want both a Bird and an Airplane to be able to Fly(). If you're thinking "strategy pattern", I would agree, but even with strategy, it's sometimes impossible to avoid duplicating code.
For example, let's say the following apply (and this is very similar to a real situation I recently encountered):
Both Bird and Airplane need to hold an instance of an object that implements IFlyBehavior.
Both Bird and Airplane need to ask the IFlyBehavior instance to Fly() when OnReadyToFly() is called.
Both Bird and Airplane need to ask the IFlyBehavior instance to Land() when OnReadyToLand() is called.
OnReadyToFly() and OnReadyToLand() are private.
Bird inherits Animal and Airplane inherits PeopleMover.
Now, let's say we later add Moth, HotAirBalloon, and 16 other objects, and let's say they all follow the same pattern.
We're now going to need 20 copies of the following code:
private IFlyBehavior _flyBehavior;
private void OnReadyToFly()
{
_flyBehavior.Fly();
}
private void OnReadyToLand()
{
_flyBehavior.Land();
}
Two things I don't like about this:
It's not very DRY (the same nine lines of code are repeated over and over again). If we discovered a bug or added a BankRight() to IFlyBehavior, we would need to propogate the changes to all 20 classes.
There's not any way to enforce that all 20 classes implement this repetitive internal logic consistently. We can't use an interface because interfaces only permit public members. We can't use an abstract base class because the objects already inherit base classes, and C# doesn't allow multiple inheritance (and even if the classes didn't already inherit classes, we might later wish to add a new behavior that implements, say, ICrashable, so an abstract base class is not always going to be a viable solution).
What if...?
What if C# had a new construct, say pattern or template or [fill in your idea here], that worked like an interface, but allowed you to put private or protected access modifiers on the members? You would still need to provide an implementation for each class, but if your class implemented the PFlyable pattern, you would at least have a way to enforce that every class had the necessary boilerplate code to call Fly() and Land(). And, with a modern IDE like Visual Studio, you'd be able to automatically generate the code using the "Implement Pattern" command.
Personally, I think it would make more sense to just expand the meaning of interface to cover any contract, whether internal (private/protected) or external (public), but I suggested adding a whole new construct first because people seem to be very adamant about the meaning of the word "interface", and I didn't want semantics to become the focus of people's answers.
Questions:
Regardless of what you call it, I'd like to know whether the feature I'm suggesting here makes sense. Do we need some way to handle cases where we can't abstract away as much code as we'd like, due to the need for restrictive access modifiers or for reasons outside of the programmer's control?
Update
From AakashM's comment, I believe there is already a name for the feature I'm requesting: a Mixin. So, I guess my question can be shortened to: "Should C# allow Mixins?"
The problem you describe could be solved using the Visitor pattern (everything can be solved using the Visitor pattern, so beware! )
The visitor pattern lets you move the implementation logic towards a new class. That way you do not need a base class, and a visitor works extremely well over different inheritance trees.
To sum up:
New functionality does not need to be added to all different types
The call to the visitor can be pulled up to the root of each class hierarchy
For a reference, see the Visitor pattern
Cant we use extension methods for this
public static void OnReadyToFly(this IFlyBehavior flyBehavior)
{
_flyBehavior.Fly()
}
This mimics the functionality you wanted (or Mixins)
Visual Studio already offers this in 'poor mans form' with code snippets. Also, with the refactoring tools a la ReSharper (and maybe even the native refactoring support in Visual Studio), you get a long way in ensuring consistency.
[EDIT: I didn't think of Extension methods, this approach brings you even further (you only need to keep the _flyBehaviour as a private variable). This makes the rest of my answer probably obsolete...]
However; just for the sake of the discussion: how could this be improved? Here's my suggestion.
One could imagine something like the following to be supported by a future version of the C# compiler:
// keyword 'pattern' marks the code as eligible for inclusion in other classes
pattern WithFlyBehaviour
{
private IFlyBehavior_flyBehavior;
private void OnReadyToFly()
{
_flyBehavior.Fly();
}
[patternmethod]
private void OnReadyToLand()
{
_flyBehavior.Land();
}
}
Which you could use then something like:
// probably the attribute syntax can not be reused here, but you get the point
[UsePattern(FlyBehaviour)]
class FlyingAnimal
{
public void SetReadyToFly(bool ready)
{
_readyToFly = ready;
if (ready) OnReadyToFly(); // OnReadyToFly() callable, although not explicitly present in FlyingAnimal
}
}
Would this be an improvement? Probably. Is it really worth it? Maybe...
You just described aspect oriented programming.
One popular AOP implementation for C# seems to be PostSharp (Main site seems to be down/not working for me though, this is the direct "About" page).
To follow up on the comment: I'm not sure if PostSharp supports it, but I think you are talking about this part of AOP:
Inter-type declarations provide a way
to express crosscutting concerns
affecting the structure of modules.
Also known as open classes, this
enables programmers to declare in one
place members or parents of another
class, typically in order to combine
all the code related to a concern in
one aspect.
Could you get this sort of behavior by using the new ExpandoObject in .NET 4.0?
Scala traits were developed to address this kind of scenario. There's also some research to include traits in C#.
UPDATE: I created my own experiment to have roles in C#. Take a look.
I will use extension methods to implement the behaviour as the code shows.
Let Bird and Plane objects implement a property for IFlyBehavior object for an interface IFlyer
public interface IFlyer
{
public IFlyBehavior FlyBehavior
}
public Bird : IFlyer
{
public IFlyBehaviour FlyBehavior {get;set;}
}
public Airplane : IFlyer
{
public IFlyBehaviour FlyBehavior {get;set;}
}
Create an extension class for IFlyer
public IFlyerExtensions
{
public void OnReadyToFly(this IFlyer flyer)
{
flyer.FlyBehavior.Fly();
}
public void OnReadyToLand(this IFlyer flyer)
{
flyer.FlyBehavior.Land();
}
}

Modify C# Class method during execution

I'd like to override a class method without inheriting the base class because it'd take a lot of time and modifications and, therefore, more and more tests. It's like this:
class TestClass{
public void initialMethod(){
...
}
}
And somewhere on the code, I'd like to do something like this:
public testMethod()
{
return;
}
test(){
changeMethod(TestClass.initialMethod, testMethod);
}
And this changeMethod function would override the TestClass initialMethod so that it'd call testMethod instead.
Inheriting and overriding the method using normal practices is not an option, as this class A is a graphic component and, inhereting it (and changing it) would break lots of code.
Edit: We don't have the base code for the TestClass, so it's not an option to modify the code there defining the initialMethod as a delegate.
Edit 2: Since this is a graphical component, the designer added a lot of code automatically. If I were to inherit this code, I would have to replace all code added by the designer. That's why I wouldn't like to replace this component.
You need the Strategy pattern.
Main steps:
Create an interface with ie. Do() signature
Your initialMethod() should call a strategy.Do(), where strategy is type of your interface
Create a class that implements this interface. Do() is your testmethod now.
Inject into your main class an instance of this class
If the job it's not so big (let's say just a color replacement or something) then I agree with Jhonny D. Cano's solution with C# (anonymous)delegates.
Edit (after edit 2)
May - just as proof-of-concept - you should inherit the class and replace all references from base class to this new. Do this, and nothing else. If it works, you can think about the next steps (new methods or delegates etc.)
You need only a new checkout from your version control system, and if it maybe fails you can abandon it. It's worth trying.
Perhaps you can do it as a delegate.
class TestClass {
public Action myAction;
public void initialMethod(){
...
}
initialMethod
public TestClass() {
myAction = initialMethod;
}
}
and then on TestMethod
public testMethod()
{
return;
}
test() {
testClassInstance.myAction = testMethod;
}
I think your best bet might be to use a AOP framework like LinFu. There's a codeproject article explaining it:
Introducing LinFu, Part VI: LinFu.AOP – Pervasive Method Interception and Replacement for Sealed Types in Any .NET Language
If 'TestClass' is something you defined, you could replace the 'initialMethod' definition with a property and delegate which can then be set to any method with a given signature. (Even anonymous ones.)
class TestClass {
Action _myMethod;
Action MyMethod {
get { return _myMethod; }
set { _myMethod = value; }
}
var tc = new TestClass()
tc.MyMethod = () -> Console.WriteLine("Hello World!");
tc.MyMethod()
The above code is untested.
The short and simple answer is: if you can't adjust the base TestClass code, no, there's no way you can modify the class to replace a method by another. Once we started doing stuff like that, we'd be in a completely different kind of language, like JavaScript.
The longer answer is: it depends on who is calling the replaced method.
If it's other classes, see if you can't implement a Proxy in between them and the unmodifiable concrete class. Whether this is doable depends on whether that class implements interfaces, or is its own interface.
If it's the class itself, then your only option is to decompile and modify the class, at design time using Reflector (or equivalent tools), or at runtime using Reflection.Emit. However, you'd have to be hurting pretty badly to go this route, as it's sure to be painful and brittle.
Unfortunately you still haven't explained what you are trying do and why. Replacing methods on the go is powerful stuff in the languages that permit it directly... There might be mocking libraries that can be twisted sufficiently far to do the reflection stuff, but then you'd be skating on thin ice.
If you don't have the code use Extension Methods.
public void doSmth(this objectYOUWANT arg)
{
//Do Something
}
Here you use the principle Closed for Modification Open for Extension.
This will add functionality to the library you don't have the source code. It's very clean to do it this way.
Edition:
In FrameWork 3.5 there is something new called Extension Methods. These kind of methods adds functionality to a closed Assembly letting you Extend in functionality a closed dll/assembly.
To use this for example you have a dll that you import, that is called Graphics.dll (you have the reference on your project)
First of all you shoud create a new static class called for example Extension:
public static class Extensions
{
}
Second, you want to add extra functionality to a class contained in Graphics.dll named ChartGraph. You will do this:
public static class Extensions
{
public static void draw(this ChartGraph g)
{
// DO SOMETHING
}
}
Third, when you instantiate a new object from the graphics.dll you now will have the new method you have created:
ChartGraph myG = new ChartGraph();
myG.draw();
As you can see there you have added new functionality without much effort without recompiling the dll, this is good if you don't have the source code.

Use new keyword if hiding was intended

I have the following snippet of code that's generating the "Use new keyword if hiding was intended" warning in VS2008:
public double Foo(double param)
{
return base.Foo(param);
}
The Foo() function in the base class is protected and I want to expose it to a unit test by putting it in wrapper class solely for the purpose of unit testing. I.e. the wrapper class will not be used for anything else. So one question I have is: is this accepted practice?
Back to the new warning. Why would I have to new the overriding function in this scenario?
The new just makes it absolutely clear that you know you are stomping over an existing method. Since the existing code was protected, it isn't as big a deal - you can safely add the new to stop it moaning.
The difference comes when your method does something different; any variable that references the derived class and calls Foo() would do something different (even with the same object) as one that references the base class and calls Foo():
SomeDerived obj = new SomeDerived();
obj.Foo(); // runs the new code
SomeBase objBase = obj; // still the same object
objBase.Foo(); // runs the old code
This could obviously have an impact on any existing code that knows about SomeDerived and calls Foo() - i.e. it is now running a completely different method.
Also, note that you could mark it protected internal, and use [InternalsVisibleTo] to provide access to your unit test (this is the most common use of [InternalsVisibleTo]; then your unit-tests can access it directly without the derived class.
The key is that you're not overriding the method. You're hiding it. If you were overriding it, you'd need the override keyword (at which point, unless it's virtual, the compiler would complain because you can't override a non-virtual method).
You use the new keyword to tell both the compiler and anyone reading the code, "It's okay, I know this is only hiding the base method and not overriding it - that's what I meant to do."
Frankly I think it's rarely a good idea to hide methods - I'd use a different method name, like Craig suggested - but that's a different discussion.
You're changing the visibility without the name. Call your function TestFoo and it will work. Yes, IMHO it's acceptable to subclass for this reason.
You'll always find some tricky situations where the new keyword can be used for hiding while it can be avoided most of the times.
However, recently I really needed this keyword, mainly because the language lacks some other proper synthax features to complete an existing accessor for instance:
If you consider an old-fashioned class like:
KeyedCollection<TKey, TItem>
You will notice that the accesor for acessing the items trough index is:
TItem this[Int32 index] { get; set; }
Has both { get; set; } and they are of course mandatory due to the inheritance regarding ICollection<T> and Collection<T>, but there is only one { get; } for acessing the items through their keys (I have some guesses about this design and there is plenty of reasons for that, so please note that I picked up the KeyedCollection<TKey, TItem>) just for illustrations purposes).
Anyway so there is only one getter for the keys access:
TItem this[TKey key] { get; }
But what about if I want to add the { set; } support, technically speaking it's not that stupid especially if you keep reasoning from the former definition of the propery, it's just a method... the only way is to implement explicitly another dummy interface but when you want to make implicit you have to come up with the new keyword, I'm hiding the accessor definition, keeping the get; base definition and just add a set stuffed with some personal things to make it work.
I think for this very specific scenario, this keyword is perfecly applicable, in particular in regards to a context where there is no brought to the { get; } part.
public new TItem this[TKey key]
{
get { return base... }
set { ... }
}
That's pretty much the only trick to avoid this sort of warning cause the compiler is suggesting you that you're maybe hiding without realizing what you are doing.

Can I force subclasses to override a method without making it abstract?

I have a class with some abstract methods, but I want to be able to edit a subclass of that class in the designer. However, the designer can't edit the subclass unless it can create an instance of the parent class. So my plan is to replace the abstract methods with stubs and mark them as virtual - but then if I make another subclass, I won't get a compile-time error if I forget to implement them.
Is there a way to mark the methods so that they have to be implemented by subclasses, without marking them as abstract?
Well you could do some really messy code involving #if - i.e. in DEBUG it is virtual (for the designer), but in RELEASE it is abstract. A real pain to maintain, though.
But other than that: basically, no. If you want designer support it can't be abstract, so you are left with "virtual" (presumably with the base method throwing a NotImplementedException).
Of course, your unit tests will check that the methods have been implemented, yes? ;-p
Actually, it would probably be quite easy to test via generics - i.e. have a generic test method of the form:
[Test]
public void TestFoo() {
ActualTest<Foo>();
}
[Test]
public void TestBar() {
ActualTest<Bar>();
}
static void ActualTest<T>() where T : SomeBaseClass, new() {
T obj = new T();
Assert.blah something involving obj
}
You could use the reference to implementation idiom in your class.
public class DesignerHappy
{
private ADesignerHappyImp imp_;
public int MyMethod()
{
return imp_.MyMethod()
}
public int MyProperty
{
get { return imp_.MyProperty; }
set { imp_.MyProperty = value; }
}
}
public abstract class ADesignerHappyImp
{
public abstract int MyMethod();
public int MyProperty {get; set;}
}
DesignerHappy just exposes the interface you want but forwards all the calls to the implementation object. You extend the behavior by sub-classing ADesignerHappyImp, which forces you to implement all the abstract members.
You can provide a default implementation of ADesignerHappyImp, which is used to initialize DesignerHappy by default and expose a property that allows you to change the implementation.
Note that "DesignMode" is not set in the constructor. It's set after VS parses the InitializeComponents() method.
I know its not quite what you are after but you could make all of your stubs in the base class throw the NotImplementedException. Then if any of your subclasses have not overridden them you would get a runtime exception when the method in the base class gets called.
The Component class contains a boolean property called "DesignMode" which is very handy when you want your code to behave differently in the designer than at runtime. May be of some use in this case.
As a general rule, if there's no way in a language to do something that generally means that there's a good conceptual reason not to do it.
Sometimes this will be the fault of the language designers - but not often. Usually I find they know more about language design than I do ;-)
In this case you want a un-overridden virtual method to throw a compile time exception (rather and a run time one). Basically an abstract method then.
Making virtual methods behave like abstract ones is just going to create a world of confusion for you further down the line.
On the other hand, VS plug in design is often not quite at the same level (that's a little unfair, but certainly less rigour is applied than is at the language design stage - and rightly so). Some VS tools, like the class designer and current WPF editors, are nice ideas but not really complete - yet.
In the case that you're describing I think you have an argument not to use the class designer, not an argument to hack your code.
At some point (maybe in the next VS) they'll tidy up how the class designer deals with abstract classes, and then you'll have a hack with no idea why it was coded that way.
It should always be the last resort to hack your code to fit the designer, and when you do try to keep hacks minimal. I find that it's usually better to have concise, readable code that makes sense quickly over Byzantine code that works in the current broken tools.
To use ms as an example...
Microsoft does this with the user control templates in silverlight. #if is perfectly acceptable and it is doubtful the the tooling will work around it anytime soon. IMHO

Categories