2

I am not able to call a non-static function from a static function (or) i want to call a javascript function from static function.

[WebMethod]
public static void add_items(string itemslist)
{
    get_price(itemslist); // Error An object reference is required for non-static

    //(or)
    ScriptManager.RegisterStartupScript(this, 
        this.GetType(), 
        "script", 
        "<Script language='javascript' "
           + "type='text/javascript'>message();</script>", 
        false); //Error in this, this
}

protected void get_price(string item_id)
{

}
2
  • 4
    If you want to call an instance method, you need an instance. How about creating one? Commented Feb 20, 2013 at 11:09
  • 2
    Is this real code? You cannot use 'this' in a static method. Commented Feb 20, 2013 at 11:48

4 Answers 4

3

Since static methods are accessible regardless whether or not you instantiated that class, accessing a class member from a static method could potentially mean that you're referencing something that doesn't yet exist in the stack or the heap, thus creating an exception at runtime.

For this reason, you can't reference non-static members inside static methods without instantiating the non-static member first, and that's why you're getting an error. Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

1

Of course you can't. If you want to do this, you need to instantiate the object containing the non-static method first.

Comments

1

The straight option is create object of class, and than call method. if you are not updating the object state (seems to me in this case), than convert the get_price method signature to static

Comments

1

Unfortunately, you can't call instance method inside a static method. Is following possible in your situation?

    [WebMethod]
    public static void add_items(string itemslist, Action<string> instanceMethod)
    {
        //get_price(itemslist);// Error An object reference is required for non-static

        instanceMethod(itemlist);
    }

    protected void get_price(string item_id)
    {

    }

Then pass get_price as argument like so.

add_items(anItemslist, get_price);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.