Click here to Skip to main content
15,887,240 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi guys,

i wonder if is there any solution to call a non static task in static method for example this is my non static task

C#
public async Task login(string user, string password)
        {

        }
and this is my static method
C#
public static void checker(string email, string password)
       {
           while (true)
           {
               login(email, password);
           }
       }
but it can't be called and i don't want to use classes for them.

What I have tried:

..................................................
Posted
Updated 6-Dec-23 21:49pm
v3
Comments
Richard MacCutchan 5-Dec-23 7:51am    
You have tagged your question C++, C#, Python, so which is it?
Ashkan X 5-Dec-23 8:05am    
yes that was a mistake sorry it's C#
Richard MacCutchan 5-Dec-23 8:15am    
Well you cannot do it, since every non-static method or property can only be accessed through its owning object.
CPallini 5-Dec-23 9:13am    
While you cannot, depending on your actual scenario there could be a workaround (for instance you can pass to the static method, the instance of the class).
Maciej Los 5-Dec-23 11:10am    
:thumbsup:

You can do it by using some global object or some local object in the static method.

But as I read C# can also start a thread on an instance method. Read the Microsoft documentation.

PS: by answering your question, I learned a bit :-)
 
Share this answer
 
No. Not directly.
A non static member always needs an object instance to work with because it is implied that it can touch instance data. and that would be impossible without the object reference.

It works in the example provided by KarstenK because the member method is wrapped in a delegate.
Which is what you could do: pass delegates.
But you'd still have to pass them somehow you cannot just 'call' a random instance method without making a delegate. Unless you use a global object.

But honestly, in cases like this, your problems are a sign that you are trying to fix the wrong problem. It is probably a sign that your 'login' method should not be an instance method. Or if it really needs to be, you should should not try to avoid using the instance.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900