Chris Cooper
Chris Cooper

Reputation: 389

Dynamic object against Interface Method

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

Upvotes: 0

Views: 151

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

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

Upvotes: 2

Related Questions