View Single Post
Old Mar 25th, 2008, 10:00 PM   #6
lectricpharaoh
SEXY SHOELESS GOD OF WAR!
 
lectricpharaoh's Avatar
 
Join Date: Jun 2005
Location: Wet west coast of Canada
Posts: 1,198
Rep Power: 5 lectricpharaoh will become famous soon enough
Re: Reflection Casting

Quote:
Originally Posted by kruptof
yeah i don't need to cast the it to my interface, but i was doing out of laziness because i need to call three methods from the plugin and atm I get each method and store it in a MethodInfo object and invoke it using that. I just wanted to use the MyInterface dot method name notation, which would have been easier.
If you do this, I believe the compiler will raise an error if the interface isn't implemented (or more specifically, if the interface method you call isn't implemented). It may also raise an error for attempting the cast to the interface:
C# Syntax (Toggle Plain Text)
  1. // possible compile-time error
  2. IPlugin pluginObject = (IPlugin)someRandomObject;
  3.  
  4. // definite compile-time error if someRandomObject doesn't
  5. // contain 'someInterfaceMethod'
  6. (IPlugin)someRandomObject.someInterfaceMethod();
This is why you need to use reflection to invoke the method; it avoids the compile-time error. However, you can just specify that a plugin writer needs to implement your interface, and let them shoulder the responsibility. I mean, if they don't implement it properly, and your reflection and type testing causes the code to simply skip the method calls, the plugin is useless anyways. Why should you jump through hoops to ensure someone else's code compiles, when it won't work anyways?

This way, you can just have your interface:
C# Syntax (Toggle Plain Text)
  1. public interface IPlugin
  2. {
  3. void someInterfaceMethod();
  4. }
Then you tell the plugin writers to implement it. If they do, they can do stuff like
C# Syntax (Toggle Plain Text)
  1. IPlugin pluginObject = (IPlugin)someObject;
  2. pluginObject.someInterfaceMethod();
If they do their job, it works. If they don't, they get a compile-time error, and can fix their code. You get your dot notation, and everyone's happy.
__________________
And once again, Probability proves itself willing to sneak into a back alley and service Drama as would a copper-piece harlot.
- Vaarsuvius, Order of the Stick
lectricpharaoh is offline   Reply With Quote