tags:

views:

37

answers:

3
namespace MyApp.MyNamespace
{
    public class MyClass:System.Web.UI.Page
    {
        private DataUtility Util = new DataUtility();
        private CookieData cd = MyClass.Toolbox.GetCurrentCookieData(HttpContext.Current);
        //below I get the error: "System.Web.UI.Util is unavailable due to its protection level"
        private int CompanyID = Util.GetCompanyIDByUser(cd.Users);

    protected override void OnLoad(EventArgs e)
    {
        //I'd like to use CompanyID here
    }           

    protected void MyEventHandler(object sender, EventArgs e)
    {
        //as well as here
    }
}

And here is DataUtility:

public class DataUtility
{
    public DataUtility() {}
    //snip
    public int GetCompanyIDByUser(int UserID)
    {
        //snip
    }
}

I've looked and DataUility as well as the method inside of it are declared public, so I'm not sure why I am getting this error.

A: 

A field initializer cannot reference the non-static members of it's own class members. If you move Util = new DataUtility(), cd = ... and CompanyID = ... into a default constructor, I believe your code could work.

Timothy Carter
I added all of that in between MyClass() { //here }, but encountered the same error.
lush
+1  A: 

You cannot reference an instance field of your class in a field initializer.

Move cd = Util.GetCompanyIDByUser(cd.Users); to the class constructor, and it will work.

The reason you're getting a seemingly incorrect error message is that your Util field is conflicting with an internal type in the .Net framework. If you rename Util to util (lowercase u), you'll get a more correct error message (but that won't solve the problem unless you move the method call to the MyClass constructor, as above).

SLaks
A: 

I just added static keyword to DataUtility initializer, and everything worked like a charm. Thanks everyone. :)

lush