Groups | Blog | Home
all groups > dotnet general > february 2007 >

dotnet general : Casting unknown type



John
2/28/2007 12:00:00 AM
How do I cast a type that can be a number of different calling pages in
asp.net. _Default is used in the example but it could be another page type.

Example :

_Default myPage = (_Default)this.Page;
myPage.Master.SearchMake = e.Item.ToString();
myPage.Master.SearchType= e.Item.ToString();
myPage.Master.SearchText = e.Item.ToString();
Server.Transfer("Search.aspx",true);

If the running pages is not of _Default, how do I do this?

Jon Skeet [C# MVP]
2/28/2007 12:00:00 AM
[quoted text, click to view]

Well, what *do* you know about the type? It looks like you know it will
have a Master property of a particular type. So encapsulate that in an
interface, make all the relevant pages implement that interface, and
cast to that interface.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
Jon Skeet [C# MVP]
2/28/2007 12:53:22 PM
[quoted text, click to view]

It's the pages that you'll be casting that need to implement an
interface first - and that's an interface that just says that their
MasterPage property returns a page of a certain type.

Unfortunately, it's not terribly clear all the types that are involved
in your question. Still, think about what they have in common - that's
what should be in the interface.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
John
2/28/2007 1:31:51 PM

[quoted text, click to view]

Well, I implemented the interface in the master page so that other pages can
implement this interface. I have to say I'm not that experienced with
interfaces and what I read isn't shedding any light on this for me.

Master Page :

interface ISearchMake
{
string GetSearchMake();
}
public partial class Main : System.Web.UI.MasterPage
{
string _SearchMake = "";

public string GetSearchMake
{
get {return _SearchMake;}
}

Single Page :

public partial class Search : System.Web.UI.Page, ISearchMake
{
protected void Page_Load(object sender, EventArgs e)
{
// Do stuff
}
}

My Control (can appear on any page) :

public partial class Search : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CF.ISearchMake MySource;
MySource = (CF.ISearchMake)Context.Handler;
Literal1.Text = MySource.GetSearchMake();
}
}
}

Gives me an error :

Error 1 'CF.Search' does not implement interface member
CF.ISearchMake.GetSearchMake()

AddThis Social Bookmark Button