Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reference a function in a class

I want to create a class with references to functions to run.
Example code which does not create a reference but runs the function upon creation

public class Jobs
{
    public List<Job> jobs;

    public Jobs()
    {
        jobs = new List<Job>()
        {
            new Job()
            {
                name = "Job 1",
                job =  func1() // This runs the function, how do I create a reference to run it later in RunJobs?
            },
            new Job()
            {
                name = "Job 2",
                job =  func1()
            }
        };

    }
    

    private async Task func1()
    {
        // do some stuff    
    }
    private async Task func2()
    {
        // do some other stuff    
    }

    public void RunJobs()
    {
        foreach(Job job in jobs) // Iterating through jobs
        {
            Console.WriteLine(job.name);
            job.job(); // I want to run the referenced function here
        }
    }

}

public class Job
{
    public string name;        
    public Task job; 

}

How can I reference func1() and func2() and run them by calling a method in the class when iterating through Jobs.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can add a delegate to your object to be invoked at a later time. C# provides some generic delegates you can use:

public class Job
{
    public string name;        
    public Func<Task> job; 
}
...
new Job()
{
      name = "Job 2",
      job =  func1
}

...
foreach(Job job in jobs) // Iterating through jobs
{
     Console.WriteLine(job.name);
     var myTask = job.job(); // I want to run the referenced function here
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading