invoking method declaration without reflection - c#

I have a base class (order) with a set of sub classes (productorder, specialorder, partsorder etc).
Only Some of these sub classes implement a particular interface (ITrackingCustomer) which has a single method declaration (object getcustdetails()).
As part of my solution all of my orders are processed in a central place, i.e. any crud methods pass through a central layer. Within this central layer I want to do the following:
If order is of type ITrackingCustomer
Then invoke method getcustdetails()
I have this working using the following code:
if (typeof(ITrackingCustomer).IsAssignableFrom(Order.GetType()))
{
MethodInfo theMethod = Order.GetType().GetMethod("getcustdetails");
object y = theMethod.Invoke(Order, null);
}
I am happy with the first part using isassignablefrom but would like to use a less performance intensive method for the second part (i.e. the reflection using invoke).
My question is:
Is there a more efficient way of doing this as I have read that using the invoke command is costly.

ITrackingCustomer ord = Order as ITrackingCustomer;
if (ord != null)
{
object y = ord.getcustdetails();
}

You can do:
if(Order is ITrackingCustomer) {
((ITrackingCustomer)Order).getcustdetails();
}

As others have mentioned, you can use the is and as operators to determine if an object is of a certain type. However, polymorphism is usually better suited for solving this type of problem.
If it is feasible, perhaps you can place a getcustdetails() method on Order. Make it virtual if it has a suitable default implementation (i.e. return no details or null), or abstract if it makes sense that all Order types must implement it. Since you have the ITrackingCustomer interface, I suspect that an abstract method won't work well. However, for Order types that implement ITrackingCustomer, you can then implement getcustdetails() accordingly.
At this point, it sounds like you would be able to do away with ITrackingCustomer, but I can't say for certain without knowing more details about how this interface is used.
Once this is done, you won't need to perform any type checks since calling Order.getcustdetails() always dispatches to the correct concrete implementation.

If you are trying to do call by name instead of invoking a member in an interface and you want to be able to call the same method thousands of times, then other than a cast (which I assume you can't do because you don't know the type) or reflection is to JIT compile the call.
Rick Strahl has a nice blog article on the performance costs of various ways to call method and the comments lead to this article which shows how to pull a delegate out to a non-virtual method.
Finally, I wrote a blog article on how to build adapter classes on the fly. What you can do with that is make a directly callable object that meets an abstract class:
public abstract class CustomerDetailsGetter {
public abstract object getcustdetails();
}
// ...
AdapterCompiler compiler = new AdapterCompiler();
AdapterFactory<CusomterDetailsGetter> factory = compiler.DefineAdapter<CustomerDetailsGetter>(Order.GetType());
// now, my code assumes you want to construct an object from whole cloth
// but the code could be changed to invoke the default constructor and set the
// adapted object.
CustomerDetailsGetter getter = factory.Construct(null)
object info = getter.getcustdetails();
Now, I need to be clear - there are only two reasons to do this:
you want to be able to have call-by-name semantics when you know the target arguments at compile time and you don't know have the target assembly, and you want your code to be CLEAN. An example of this is code that knows it wants to create and use a particular object, but doesn't know if the assembly will be available until run time and is forbidden to have a reference.
you want to call object methods a la reflection, but want to do this fast, fast, fast and will be calling them thousands or millions of times.
If it's a "call once" thing, you're way better off writing a helper method to do what you want.

Related

Is there a way to hide/show certain methods when instantiating an object?

This question came to mind while I was writing a class that iterates over a list, with methods next() and previous() that will continuously loop (e.g. if at the last object, return it, and then reset index to 0)
In the constructor I was pondering adding a boolean variable, which if true would just act like a regular iterator with only next() methods and no looping. In this case, having the method previous() would make no sense. So I'm curious, is it possible to hide the previous() method in this case. Is it possible to achieve this somehow in Java or C#?.
What about other languages?
C#
It is possible by making the two methods part of two different interfaces, and casting the object to one of the two interfaces. For example:
interface ILoopingIterator
{
void Next();
void Previous();
}
interface INonLoopingIterator
{
void Next();
}
class PlaysItBothWays : ILoopingIterator, INonLoopingIterator
{
void ILoopingIterator.Next()
{
this.NextCore();
}
void ILoopingIterator.Previous()
{
// since this code will never be shared anyway, put it here
}
void INonLoopingIterator.Next()
{
this.NextCore();
}
private void NextCore()
{
// do stuff here; this method only exists so that code can be shared
}
}
Note that I have made the class implement both interfaces explicitly; this way, users of instances are forced to select which "mode" they want to use the class in. You could implement only one interface explicitly instead (providing a "default" mode that can be changed).
and now:
var looping = (ILoopingIterator) new PlaysItBothWays(); // selects mode A
var nonLooping = (INonLoopingIterator) new PlaysItBothWays(); // selects mode B
Of course this does not stop anyone from casting the instance to the "other" interface if they want to, but if the programmer wants to subvert their own code they can also use reflection which allows much more than that.
Java
In Java, the above is not possible. You can come close by having the class expose methods that return instances of one of the two interfaces, and using the returned value. Of course then the object is really a factory and not a service provider, so that's feels like cheating on the problem.
class PlaysItBothWays
{
public ILoopingIterator asLooping() { return /* something */ }
public INonLoopingIterator asNonLooping() { return /* something else */ }
}
Rather than passing a boolean to a constructor, you should simply use inheritance.
Suppose you have a base iterator that supports only next(). If that's the only functionality you need, instantiate it.
To provide more functionality, inherit from this base iterator, make a class called TwoWayIterator or something like that, and provide a previous() method.
Both of these classes will share a common super class, so you can treat them as one, and you can hide the previous() method by treating an instance as its base class.
It is not possible to hide a method like that in a statically typed language. The best you can do is implement the method to throw an exception (or equivalent) if the method is called.
There are tricks that you can do to make it appear like the methods are not there. For instance, having the class implement two interfaces, and using different factory methods to create them. However, they don't work if the constructor is used directly, or if you want the choice to be determined by the value of a constructor or factory method parameter.
Not in Java. You can't "Hide" methods at runtime. I'd suggest you to create Two interfaces
, one with the next method and the other one extending the first one and adding the "previous" method. Then, you can have 2 factories methods to create an instance of one of these classes.
Please take a look to the Java "Iterator" class
interface Iterator<T> {
T next();
}
interface LoopingIterator<T> extends Iterator<T>{
T previous();
}
Then you can cast them. Similar to the previous C# answer
You can't hide class members at run time (well, not in C# anyway - not sure about Java). If you so worried about Previous() method being used in the context where it is not doing anything useful, then simply have it throw InvalidOperationException in that case.
It is also worth noting that .NET already has standard "iterator" interface. It is called IEnumerable (and generic version IEnumerable<T>) and is forward-only.

Preferred style (delegates over abstract Classes or interfaces)

I have a utility class library I am writing. A have written a factory class that is generic enough that with a few delegates passed in from the caller it can be reused in many different situations. However, one of my colleagues suggested that I use an abstract class or an interface so it is more explicit what functions needed to be overridden. In the model I have created to use the library you would then need to override 2 classes instead of just one. What criteria determines when it is appropriate to use delegate functions or interfaces.
Using a delegate pattern.
Class A
{
Func<string , ReultClass> fun1 {get;set;}
FactoryObj CreateObj()
{
return fun1("")
}
}
Using an interface pattern
Class B
{
InterfaceObj{get;set;}
FactoryObj CreateObj()
{
return InterfaceObj.fun1("")
}
}
If the design is such that the class depends on another class (even a simple class), I would recommend the interface approach, since the object does have to depend on outside code:
interface IA
{
ResultClass Fun1(string arg);
}
In this case, you can still use delegates; I usually write my "anonymous" classes (as Microsoft calls them) with explicit interface implementations, so the name of the delegate property is the same as the name of the interface method it implements:
class AnonymousA : IA
{
Func<string, ResultClass> Fun1 { get; set; }
ResultClass IA.Fun1(string arg) { return this.Fun1(arg); }
}
If there are generics involved (e.g., IA<ResultClass> and the corresponding AnonymousA<ResultClass>), then it's useful to define a factory class, just to clean up the creation syntax:
static class Anonymous
{
public static IA<ResultClass> A<ResultClass>(Func<string, ResultClass> fun1)
{ return new AnonymousA<ResultClass> { Fun1 = fun1 }
}
I would think you would want to change the signature of the method. Instead of making the delegate a property on your class, make that a parameter you need to pass in. Then, you can't even invoke your CreateObj method without passing in the required data, and the signature itself tells you what you need to pass for the method call to be successful.
does/should the factory know about the various 'concrete' versions? Are there a fixed, relatively low number of specific concrete versions? If yes for either, IMHO the abstract base is a good approach. If the caller should be able to pass in 'arbitrary' code, you could either pass in delegates, or if multiple callers may want to handle/interpret the same data, expose it as events from the base and let the various callers hook up and do their interpretation.
Unfortunately, as SLaks mentions, it kind of depends on the specific situation - it's hard to make any kind of blanket statements - even the above one is likely to be a bad idea in some situations :)
Using wrapper classes, it's possible to do anything that can be done with delegates using interfaces, and vice versa. To determine which is appropriate for a given situation, examine the common usage patterns.
For example, suppose one wants to construct at run-time a list of actions that will need to be performed when a certain object is disposed. The most common action will be to call Dispose on an object of type IDisposable, but in some cases it may be necessary to do something else (e.g. unsubscribe an event handler).
One approach would be to maintain a list of MethodInvoker delegates and invoke each in turn(*). If cleanup will require calling Dispose on an object, make a new delegate for thatObject.Dispose() and add it to the list. An alternative approach would be to keep a list of IDisposable objects, and handle other actions by creating a class called InvokeOnDispose which holds a MethodInvoker, and invokes it when Dispose is called.
The former approach would require creating a new delegate for each cleanup action, whether it simply involved calling Dispose on something, or did something else. The latter approach would not require creating any new object instances when adding an IDisposable object to the list, but adding some other action would require creating an InvokeOnDispose object in addition to a delegate.
(*) One could simply use a MulticastDelegate rather than a list of delegates, but in some circumstances (like object cleanup) an exception thrown from one cleanup operation should probably not disrupt the operation of others. While one could assemble the collection of cleanup operations using a MulticastDelegate and then use GetInvocationList to run each within a separate 'try-catch' block, it would be easier and more efficient to simply use a list of delegates from the get-go.

Using implicit conversion as a substitute for multiple inheritance in .NET

I have a situation where I would like to have objects of a certain type be able to be used as two different types. If one of the "base" types was an interface this wouldn't be an issue, but in my case it is preferable that they both be concrete types.
I am considering adding copies of the methods and properties of one of the base types to the derived type, and adding an implicit conversion from the derived type to that base type. Then users will be able treat the derived type as the base type by using the duplicated methods directly, by assigning it to a variable of the base type, or by passing it to a method that takes the base type.
It seems like this solution will fit my needs well, but am I missing anything? Is there a situation where this won't work, or where it is likely to add confusion instead of simplicity when using the API?
EDIT: More details about my specific scenario:
This is for a potential future redesign of the way indicators are written in RightEdge, which is an automated trading system development environment. Price data is represented as a series of bars, which have values for the open, low, high, and close prices for a given period (1 minute, 1 day, etc). Indicators perform calculations on series of data. An example of a simple indicator is the moving average indicator, which gives the moving average of the most recent n values of its input, where n is user-specified. The moving average might be applied to the bar close, or it could be applied to the output of another indicator to smooth it out.
Each time a new bar comes in, the indicators compute the new value for their output for that bar.
Most indicators have only one output series, but sometimes it is convenient to have more than one output (see MACD), and I want to support this.
So, indicators need to derive from a "Component" class which has the methods that are called when new data comes in. However, for indicators which have only one output series (and this is most of them), it would be good for them to act as a series themselves. That way, users can use SMA.Current for the current value of an SMA, instead of having to use SMA.Output.Current. Likewise, Indicator2.Input = Indicator1; is preferable to Indicator2.Input = Indicator1.Output;. This may not seem like much of a difference, but a lot of our target customers are not professional .NET developers so I want to make this as easy as possible.
My idea is to have an implicit conversion from the indicator to its output series for indicators that have only one output series.
You don't provide too many details, so here is an attempt to answering from what you provide.
Take a look at the basic differences:
When you have a base type B and a derived type D, an assignment like this:
B my_B_object = my_D_object;
assigns a reference to the same object. On the other hand, when B and D are independent types with an implicit conversion between them, the above assignment would create a copy of my_D_object and store it (or a reference to it if B is a class) on my_B_object.
In summary, with "real" inheritance works by reference (changes to a reference affect the object shared by many references), while custom type conversions generally work by value (that depends on how you implement it, but implementing something close to "by reference" behavior for converters would be nearly insane): each reference will point to its own object.
You say you don't want to use interfaces, but why? Using the combo interface + helper class + extension methods (C# 3.0 and .Net 3.5 or newer required) can get quite close to real multiple inheritance. Look at this:
interface MyType { ... }
static class MyTypeHelper {
public static void MyMethod(this MyType value) {...}
}
Doing that for each "base" type would allow you to provide default implementations for the methods you want to.
These won't behave as virtual methods out-of-the-box; but you may use reflection to achieve that; you would need to do the following from within the implementation on the Helper class:
retrieve a System.Type with value.GetType()
find if that type has a method matching the signature
if you find a matching method, invoke it and return (so the rest of the Helper's method is not run).
Finally, if you found no specific implementation, let the rest of the method run and work as a "base class implementation".
There you go: multiple inheritance in C#, with the only caveat of requiring some ugly code in the base classes that will support this, and some overhead due to reflection; but unless your application is working under heavy pressure this should do the trick.
So, once again, why you don't want to use interfaces? If the only reason is their inability to provide method implementations, the trick above solves it. If you have any other issue with interfaces, I might try to sort them out, but I'd have to know about them first ;)
Hope this helps.
[EDIT: Addition based on the comments]
I've added a bunch of details to the original question. I don't want to use interfaces because I want to prevent users from shooting themselves in the foot by implementing them incorrectly, or accidentally calling a method (ie NewBar) which they need to override if they want to implement an indicator, but which they should never need to call directly.
I've looked at your updated question, but the comment quite summarizes it. Maybe I'm missing something, but interfaces + extensions + reflection can solve everything multiple inheritance could, and fares far better than implicit conversions at the task:
Virtual method behavior (an implementation is provided, inheritors can override): include method on the helper (wrapped in the reflection "virtualization" described above), don't declare on the interface.
Abstract method behavior (no implementation provided, inheritors must implement): declare method on the interface, don't include it on the helper.
Non-virtual method behavior (an implementation is provided, inheritors may hide but can't override): Just implement it as normal on the helper.
Bonus: weird method (an implementation is provided, but inheritors must implement anyway; they may explicitly invoke the base implementation): that's not doable with normal or multiple inheritance, but I'm including it for completeness: that's what you'd get if you provide an implementation on the helper and also declare it on the interface. I'm not sure of how would that work (on the aspect of virtual vs. non-virtual) or what use it'd have, but hey, my solution has already beaten multiple inheritance :P
Note: On the case of the non-virtual method, you'd need to have the interface type as the "declared" type to ensure that the base implementation is used. That's exactly the same as when an inheritor hides a method.
I want to prevent users from shooting themselves in the foot by implementing them incorrectly
Seems that non-virtual (implemented only on the helper) will work best here.
or accidentally calling a method (ie NewBar) which they need to override if they want to implement an indicator
That's where abstract methods (or interfaces, which are a kind of super-abstract thing) shine most. The inheritor must implement the method, or the code won't even compile. On some cases virtual methods may do (if you have a generic base implementation but more specific implementations are reasonable).
but which they should never need to call directly
If a method (or any other member) is exposed to client code but shouldn't be called from client code, there is no programmatic solution to enforce that (actually, there is, bear with me). The right place to address that is on the documentation. Because you are documenting you API, aren't you? ;) Neither conversions nor multiple inheritance could help you here. However, reflection may help:
if(System.Reflection.Assembly.GetCallingAssembly()!=System.Reflection.Assembly.GetExecutingAssembly())
throw new Exception("Don't call me. Don't call me!. DON'T CALL ME!!!");
Of course, you may shorten that if you have a using System.Reflection; statement on your file. And, BTW, feel free to change the Exception's type and message to something more descriptive ;).
I see two issues:
User-defined type conversion operators are generally not very discoverable -- they don't show up in IntelliSense.
With an implicit user-defined type conversion operator, it's often not obvious when the operator is applied.
This doesn't been you shouldn't be defining type conversion operators at all, but you have to keep this in mind when designing your solution.
An easily discoverable, easily recognizable solution would be to define explicit conversion methods:
class Person { }
abstract class Student : Person
{
public abstract decimal Wage { get; }
}
abstract class Musician : Person
{
public abstract decimal Wage { get; }
}
class StudentMusician : Person
{
public decimal MusicianWage { get { return 10; } }
public decimal StudentWage { get { return 8; } }
public Musician AsMusician() { return new MusicianFacade(this); }
public Student AsStudent() { return new StudentFacade(this); }
}
Usage:
void PayMusician(Musician musician) { GiveMoney(musician, musician.Wage); }
void PayStudent(Student student) { GiveMoney(student, student.Wage); }
StudentMusician alice;
PayStudent(alice.AsStudent());
It doesn't sound as if your method would support a cross-cast. True multiple inheritance would.
An example from C++, which has multiple inheritance:
class A {};
class B {};
class C : public A, public B {};
C o;
B* pB = &o;
A* pA = dynamic_cast<A*>(pB); // with true MI, this succeeds
Then users will be able treat the derived type as the base type by using the duplicated methods directly, by assigning it to a variable of the base type, or by passing it to a method that takes the base type.
This will behave differently, however. In the case of inheritance, you're just passing your object. However, by implementing an implicit converter, you'll always be constructing a new object when the conversion takes place. This could be very unexpected, since it will behave quite differently in the two cases.
Personally, I'd make this a method that returns the new type, since it would make the actual implementation obvious to the end user.
Maybe I'm going too far off with this, but your use case sounds suspiciously as if it could heavily benefit from building on Rx (Rx in 15 Minutes).
Rx is a framework for working with objects that produce values. It allows such objects to be composed in a very expressive way and to transform, filter and aggregate such streams of produced values.
You say you have a bar:
class Bar
{
double Open { get; }
double Low { get; }
double High { get; }
double Close { get; }
}
A series is an object that produces bars:
class Series : IObservable<Bar>
{
// ...
}
A moving average indicator is an object that produces the average of the last count bars whenever a new bar is produced:
static class IndicatorExtensions
{
public static IObservable<double> MovingAverage(
this IObservable<Bar> source,
int count)
{
// ...
}
}
The usage would be as follows:
Series series = GetSeries();
series.MovingAverage(20).Subscribe(average =>
{
txtCurrentAverage.Text = average.ToString();
});
An indicator with multiple outputs is similar to GroupBy.
This might be a stupid idea, but: if your design requires multiple inheritance, then why don't you simply use a language with MI? There are several .NET languages which support multiple inheritance. Off the top of my head: Eiffel, Python, Ioke. There's probable more.

In C#, how can I downcast a previously upcasted object without knowing it's type?

I have an interface method
public void Execute(ICommand command);
which needs to pass known subtypes of ICommand to an apropriate Handle(SpecificCommand command) method implementation and do some generic handling of unknown types. I am looking for a universal (i.e. not requiring a giant switch) method of doing so, something similar to
Handle(command as command.GetType()); // this obviously does not compile
I know I could register the handlers somehow, e.g. store them as delegates in a dictionary, but this still requires duplicating the handling logic (once in the specific Handle(...) method signature, once in the delegate reqistration). If I populate the dictionary by inspecting my class with reflection (looking for Handle(XXX command) methods), I'll get a performance hit.
To summarize: how can I downcast an object (upcasted by the call to Execute(ICommand command)) to invoke a method requiring a concrete type without knowing which type it is at compile time.
Well, the "correct" answer is that Handle() should be a method in ICommand, so that instead of Handle(command), you'd be saying command.Handle().
The cast is emitted at compile-time, so you need to know the type at compile-time. The overloading is also determined at compile-time - so by the time you actually know the concrete type to use, it's too late.
I don't see that you'd actually be duplicating any logic by using delegates. Alternatively, if you do it with reflection, you can build delegates very easily using Delegate.CreateDelegate - you'll only get a performance hit once, and after that it'll be very fast. See my blog entry about Delegate.CreateDelegate for more information.
I think I'd decide to use a hand-built dictionary or one built with reflection based on how many methods I had and how often they change. You'll probably find KeyedByTypeCollection useful for the dictionary.
You can't, and why would you want to?
That's the whole reason we have polymorphism. If you want to have custom behaviour that is specific to certain types, then the behaviour should live in the type itself and be invoked via a function declared in the base class type.
I've tried working out a way which would work using Double Dispatch (http://en.wikipedia.org/wiki/Double_dispatch), but it seems that you have a situation where the number of classes implementing ICommand and those implementing Execute() can vary at run-time (or, at least between compile & run-time, which is essentially the same thing), so the only solution I can see it use the dictionary as Jon Skeet propsed.

Best Practice for Loading Object from Serialized XML in C#

Greetings,
I have a particular object which can be constructed from a file, as such:
public class ConfigObj
{
public ConfigObj(string loadPath)
{
//load object using .Net's supplied Serialization library
//resulting in a ConfigObj object
ConfigObj deserializedObj = VoodooLoadFunction(loadpath);
//the line below won't compile
this = thisIsMyObj;
}
}
I want to, in essense, say "ok, and now this object we've just deserialized, this is the object that we in fact are." There are a few ways of doing this, and I'm wondering which is considered a best-practice. My ideas are:
Build a copy-into-me function which copies the object field by field. This is the current implementation and I'm pretty sure its a horrible idea since whenever a new member is added to the object I need to also remember to add it to the 'copy-into-me' function, and there's no way that's maintainable.
Build a static method for the ConfigObj class which acts as a de-facto constructor for loading the object. This sounds much better but not very best-practice-y.
I'm not entirely happy with either of the two, though. What is the acknowledged best practice here?
Your second option is what is called a factory method and is a common design technique. If you do use this technique, you may find that you need to know the type of class you will load before you actually load the class. If you run into this situation, you can use a higher level type of factory that looks at the stream and calls the factory method for the appropriate type of class.
There's nothing wrong with having a static method instead of a constructor. In fact, it has a number of advantages.
I always go with the static method. Usually it's kind of a hierarchy which is loaded, and therefore only the root object needs the method. And it's not really an unusual approach in the .NET framework (e.g. Graphics.FromImage), so it should be fine with users of your class.

Categories

Resources