Search code examples
c#asp.netvs-web-site-projectapp-code

Unable to access class from app_code


I have a web site(not web app) which has a default.aspx and default.aspx.cs. And it has an App_Code folder with class A in it. So default.aspx.cs. Looks like:

namespace test1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }
}

And class A:

namespace test1
{
    public class A
    {
        _Default mDefaultRef;
        public pageLogicIndividual(_Default defaultRef)
        {
            mDefaultRef = defaultRef;
        }
    }
}

I can use A in _Default. eg. if I type test1., while working in class _Default, the IntelliSense will show both classes. But if I type test1., while working in class A, the IntelliSense will only show A. Why can't I use _Default in A?

Error : the type or namespace name does not exist in the namespace (are you missing an assembly reference )

Edit: I'll try to clarify. While working in the .cs file where class _Default resides I can type test1., which is the namespace, and the intellisense will show me class _Default and Class A. But if I'm working in the .cs file where class A resides and type test1., which is the namespace, then the intellisense will only show me class A.


Solution

  • In a nutshell, you cannot access page classes from App_code classes.
    This restriction comes from website project compilation model. Special App_code folder contains shared classes (and possibly other resources) which are available to pages (and to each other). During compilation App_code is compiled first in a single assembly. This is the key point. Pages, controls and MasterPages are compiled in another assembly(ies) which may have references to the App_code assembly (but not vise versa). So this is one-way road.
    No namespace declaration should circumvent this behavior.
    Pages can see each other in ASP namespace (ASP.default_aspx) but pages usually don't have public properties / methods (user controls .ascx usually have).
    Read better explanation on MSDN Code-Behind Pages