Question

I'm working on an asp.net web application in c#. I have a public class called GetUser. In that class I have a method called GetCurrentUser. The method is as follows:

    public MobileUser GetCurrentUser(MDMDataContext dc, string userCode)
    {
        using (dc)
        {
            dc.ObjectTrackingEnabled = false;
            var currentUser =
                from MobileUser in dc.MobileUsers
                where MobileUser.UserCode == usercode                     
                select MobileUser;

            MobileUser mu = new MobileUser();
            mu = currentUser.Single();

            return mu;
        }
    }

But when I try to use the GetCurrentUser instance method as follows:

using (MDMDataContext dc = new MDMDataContext())
        {
            GetUser.GetCurrentUser(dc, "ABCD");
        }

I get the following error, "An object reference for the non-static field, method or property '....GetUser.GetCurrentUser....'

But if I add the static keyword to the function, the error goes away. Can somebody please demystify this concept for me?

Was it helpful?

Solution

Your method is an instance method, which means you need an instance on which to run it:

using (MDMDataContext dc = new MDMDataContext())
{
        GetUser user = new GetUser();
        user.GetCurrentUser(dc, "ABCD");
}

The static keyword means that the method is static, and available for the type as a whole, not tied to a specific instance. That's why you can call it using the class name (and must call it that way) when it's marked static.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top