Dynamic object against Interface Method - c#

I'm rewriting a desktop solution and I have the main root Form, that contains Properties that should be accessible by other elements of the application.
You could use an Interface method to get the property or your could get the Form as a dynamic object and query the property. Code example below.
Interface-based approach
public interface IUersInterfaceMainScreenGet
{
dynamic GetClientDetails();
}
The forms interface-implementation looks like this:
public dynamic GetClientDetails()
{
return currentClients;
}
Calling the Interface
var mainScreen = (InterfaceProject.IUersInterfaceMainScreenGet)System.Windows.Forms.Application.OpenForms["mainScreenForm"];
return mainScreen.GetLastBodyPluginFormName();
Dynamic-based appraoch
dynamic form = Application.OpenForms["MainScreenForm"];
form.currentClients
Both instance needs to get the current Active form, but Which once would be the best in practice to memory usage?
With the Interface the Property that I want to get can be private, but for Dynamic it needs to be public

Your question is quite hard to understand. However I have a guess on what you mean.
When you have your interface you can get the clients details via a method called GetClientDetails. On the form its implementation simply returns the private field (not property) currentClients.
Usually it´s a good idea to know the types you handle with, so using interfaces is a good idea as you have compile-time checks on what you can access and what not. In your case you kno that the object returned from Forms.Application.OpenForms["mainScreenForm"] has a method for accessing the client-details. When using only dynamic you have no knowledge at all on the contained object, you could do everything with it - whereas the most will fail at runtime. But why do you want to throw away knowledge that you already have?
So my basic suggestion is: allways use strongly-typed interfaces. Only in a few seldom circumstances you may actually need dynamic.
Concerning the memory-footprint there is no difference between both solutions. What counts is the memory of your actual instance, which is the same, no matter on how you access the data. So you need a field in both cases. The only difference is how you access that field, one time you this happens directly (dynamic) and on the interface you access it by calling the method.
So there is no difference on the following two statements concerning memory-footprint:
var form = (IUersInterfaceMainScreenGet)Application.OpenForms["mainScreenForm"];
return form.GetClientDetails();
And
dynamic form = Application.OpenForms["MainScreenForm"];
return form.currentClients

Related

Brief understanding of interfaces

I have an interface which says setMaster();
and 2 classes from which i`m setting the respective master pages based on the scenario.
I need to understand what the following code means:
Control pageControl = LoadControl(pageControlPath);
if (pageControl is IVariableMasterPageControl)
{
((IVariableMasterPageControl)pageControl).setMaster();
}
My Code:
Interface:
interface IVariableMasterPageControl
{
void setMaster();
}
Classes:
public class VariableMasterControl1 : System.Web.UI.UserControl, IVariableMasterPageControl
{
public void setMaster()
{
this.Page.MasterPageFile = ("~/ui/" + SiteConfiguration.UIID + "/MasterPageOne.Master");
}
}
The code you are showing loads a UserControl dynamically. The call to LoadControl method returns an instance of type Control. This can be any control that might or might not implement the interface IVariableMasterPageControl. So, if you want to call the setMaster method, you need to check whether the control implements the interface before accessing the control over the interface. This is what the if statement is doing.
The is Statement checks whether an object is compatible with a given type so that it can be cast to that type. In your case, the line
if (pageControl is IVariableMasterPageControl)
checks whether pageControl implements IVariableMasterPageControl so that it can cast it safely in the next line.
As you need the reference to the interface afterwards, an alternative would be to use the as operator:
Control pageControl = LoadControl(pageControlPath);
var varMasterPageCtrl = pageControl as IVariableMasterPageControl;
if (varMasterPageCtrl != null)
varMasterPageCtrl.setMaster();
It seems to me that you are doing custom ASCX controls, some of which implement the interface IVariableMasterPageControl. The code which you have trouble understanding is checking, if the control in question implements the interface or not. If it does, it accesses the method setMaster() of the control - which obviously had to be implemented.
The code
if (pageControl is IVariableMasterPageControl)
Is the part where the check is done to see if the control actually implements the interface or not. This can also be done in the following manner;
if (pageControl.GetType() == typeof(IVariableMasterPageControl))
Take a look at this link: How to compare types. May help you out comparing types and understanding more in depth the concept.
in this case, the is keyword basically says: "if this instance of PageControl implements the interface IVariableMasterPageControl, then call the interface's SetMaster() method for that PageControl."
The check using the is keyword makes sure, that your object actually has a method SetMaster() to call. You could iterate through a bunch of PageControl objects, but there's no guarantee that all of them would implement the interface. Calling a non-existent method without a check would certainly either cause an Exception or could even call the wrong code (if, say, one of the PageControl objects implements an other interface that just happens to also define a method SetMaster()).

Instantiating an Internal class and casting it as a given type

Following up on InternalsVisibleTo. I have looked at c# Instantiating Internal class with private constructor, and this has helped but I'm trying to cast the returned object as the internal type and, honestly I'm not 100% that that is possible.
I'm trying the route of Reflection to fix this issue, but I'm having a tough time trying to figure out how to instantiate an internal type with private methods using reflection. I can go as far as pulling the type and getting the constructor and creating an object.
How would I preform the cast of the object if the type I wish to cast is an internal type.?
public object InitPrivateCoreObjects(string Type)
{
Assembly Core = Assembly.Load("Stuff.Core, Version=0.3.3881.21340, Culture=neutral, PublicKeyToken=4fe470e63e2d354e");
Type TypeToReflect = Core.GetType("Stuff.Core.AssemblyWithIdentifer");
object o = Activator.CreateInstance(TypeToReflect);
MethodInfo mi = TypeToReflect.GetMethod("AssemblyWithIdentifer");
object newObject = mi.Invoke(o,null);
//alternatively
//ConstructorInfo ctor = TypeToReflect.GetConstructor(new Type[]{TypeToReflect.GetType()});
//ctor.Invoke(newObject, null);
return newObject;
}
I can get the type of the internal class,
I can call the constructor and instantiate an object of the type. However, since I don’t have any access to the internal type I can’t cast it and manipulate it from there.
I understand I can use Reflection.Emit to create a new class based on that type, but if I'm going that route then I might as well just copy the entire contents of the project I'm trying to access into my test project. This would be really wastefully and pointless and would require me to throw in stuff from other projects and creating a mess and it's absolutely not the route I want to go at this time.
I've seen examples accessing individual methods and properties but none that instantiate an entire class. I'm not 100% sure it's possible since in the order of operations reflection happens before access modifiers are looked at.
Can this be done, and if so, how?
For clairification sake I wanted to use the instantiated object for testing purposes and [Assembly:InternalsVisibleTo("")] wasn't working due to bug which I'm currently working around. See here for original question.
Given that you only know the type at execution time, there's really no such concept as "returning the object as the internal type". Think about what you'd want the method signature to look like... there's no way you could express it.
If the calling code knows about it in a strongly typed way, you should make the code generic instead:
public T InitPrivateCoreObjects<T>()
{
Type type = typeof(T);
...
return (T) newObject;
}
... but if the calling code doesn't know about it, that's not helpful to it.
If you could explain more about why you think you want this ability, we could try to suggest alteratives.
I can use Reflection.Emit to create a new class based on that type
Not really: code generated using Reflection.Emit follows the same rules as your own C#. You can't use it to bypass internal protection.
I've seen examples accessing individual methods and properties
That's what you'll need to do: use reflection to look up and invoke individual methods and properties.
A couple of alternatives:
Modify the internal class to implement some interface, and make that interface public. Call methods on the interface as normal.
Get [InternalsVisibleTo] working. This is the right way to go.
This is not really a direct answer to your question, but you may find this useful:
ExposedObject
If you don't have access to the internal type, nor does that type implement any public interface that you consider sufficient to interact with it, but you know beforehand the names and signatures of members on that type, this is probably your best choice.

method overloading and polymorphism

I'm writing a .NET web application in which administrators can customize the various data entry forms presented to their users. There are about half a dozen different field types that admins can create and customize (i.e. text, numeric, dropdown, file upload). All fields share a set of base attributes/behaviors (is the field required? Will it have a default field value?). There are also a series of field specific attributes/behaviors (i.e dropdown has a data source attribute, but text field does not). I'm leaving out many other characteristics of the problem domain for simplicity's sake.
The class hierarchy is straightforward: An abstract superclass that encapsulates common behaviors/attributes and about half a dozen concrete subclasses that deal with field specific stuff.
Each field type is rendered (i.e. mapped to) as a specific type of .NET server control, all of which derive from System.Web.UI.Control.
I created the following code to map values between the field domain objects and their corresponding UI control:
public static void Bind(Control control, IList<DocumentFieldBase> fieldBaseList)
foreach (DocumentFieldBase fieldBase in fields){
if (typeof (DocumentFieldText).IsInstanceOfType(fieldBase)){
TextBox textbox = (TextBox) control;
textbox.Text = (fieldBase as DocumentFieldText).GetValue();
}
if (typeof (DocumentFieldDropDown).IsInstanceOfType(fieldBase)){
DropDown dropDown= (DropDown) control;
dropDown.Text = (fieldBase as DocumentFieldSelectOne).GetValue().Text;
dropDown.DataSource= (fieldBase as DocumentFieldSelectOne).DataSource;
dropDown.Id= (fieldBase as DocumentFieldSelectOne).GetValue().Id;
}
//more if statements left out for brevity
}
}
I want to ditch those ungodly if statements that perform type checking. The approach I was shooting for was to create a method overload for each combination of field/control using subclass typing. For example:
public static void Bind(TextBox control, DocumentFieldText fieldText){
//some implementation code
}
public static void Bind(DropDown control, DocumentFieldDropDown fieldDropDown){
//some implementation code
}
I was hoping that I could then rely on .NET to call the appropriate overload at runtime using the specific subclass being used: For example:
foreach (DocumentFieldBase field in fields){
Control control = FindControl(field.Identifier);
Bind(control, field)
}
Unfortunately, the compiler chokes when I try this:
Argument '1': cannot convert from 'System.Web.UI.Control' to 'TextBox'.
If I have to cast the first argument to TextBox, I'm back to performing type checking myself and defeats the whole purpose of this exercise.
Is what I'm trying to achieve a) possible and b) a good idea?
Prior to C# 4, all overloading is done at compile time. You have to use double dispatch or the visitor pattern to effectively overload at execution time, and that gets messy quickly.
In C# 4, you could declare a variable as dynamic and let it all get sorted out at execution time:
foreach (DocumentFieldBase field in fields){
dynamic control = FindControl(field.Identifier);
Bind(control, field)
}
Obviously that's not much help at the moment though (unless you're using VS2010b1).
One option is to use a map from Type to Action<object> but then you get inheritance issues... (you'd potentially have to keep working up the type hierarchy from the concrete type up to object until you found an entry in the map). You'd also still need to cast to the right type within the action :(
The "dispatch" tag on this question is quite appropriate: what you want is called "multiple dispatch". C# (like most mainstream languages) only supports "single dispatch", where the method to be executed is selected solely on the (runtime) type of the object you call the method on, not on the (runtime) type of its arguments.
The visitor pattern can often be used to work around this. The idea is that you give DocumentFieldBase a method (that you override in concrete subclasses) which calls a method on Control (also overridden in concrete subclasses) that does the actual work.
Unfortunately, the source code of the Control class is probably not under your control*... so you'll have to resort to an even more hackish solution. The accepted answer to this question provides one that uses reflection.
*Extension methods are just syntactic sugar for static methods, and are thus resolved at compile time and of no use in this scenario.
Couldn't you have an abstract, non-static Bind() method in DocumentFieldBase, then do the downcasting inside each concrete class's implementation of it? Each DocumentFieldBase class knows what type of Control it's getting, doesn't it?

invoking method declaration without reflection

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.

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