Monday, January 19, 2009

The smart way to removing multiple memory applet references in Windows Mobile

I wrote an article recently to get over the problem of multiple references to an application in Windows Mobile memory applet when loading multiple forms here.

Thanks to monxalo's suggestion to using extension methods support in the .NET 3.5 we can design a more elegant solution.

I just created a simple class named FormExtensions in my UI namespace with the following code:
public static class FormExtension
{
public static DialogResult ShowDialog(this Form owner, Form form)
{
form.Owner = owner;
return form.ShowDialog();
}
}
Nothing too complex here. So in our client code where we would normally load another form we could now code something like the following:
private void OnButtonClick(object sender, EventArgs e)
{
this.ShowDialog(new Form2());
}
This assumes the FormExtensions class is in the same namespace as the UI layer. If not you'd have to fully qualify the extension class. I recomend putting it in the same namespace as the UI though.

3 comments:

Daniel Marbach said...

You are saying that

"In order for this to work ensure you import and use System.Linq (for method extension support)."

This is not really true. For extension methods you don't need to import System.Linq. You only need to import System.Linq if you want the Linq Extension in your code.

For using your extension method you only need to import the namespace where your extension method is contained.

But smart solution though!

Daniel

Simon Hart said...

@Daniel:

Thanks for spotting that, you're right and I've amended the post.

Thanks,
Simon.

monxalo said...

After reading this post, it isn't quite what i was thinking.

I was thinking on adding as extension the Form.ShowDialog(IWin32Window) from .NET Framework to the .NET CF that shows a form as a modal dialog box with a specified owner.

But i accidentally switched the arguments, so it became like that:
(this Form owner, Form form)

using the code:
this.ShowDialog(new Form2());

where it should be:
(this Form form, Form owner)

using the code:
Form2 form = new Form2();
form.ShowDialog(this);


Anyway, we can use both cases :).