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

c# – Is there a way to assign void method to a variable?

I have a repository which contains some methods. However I have a method that I am trying to assign to a variable. But it doesn’t work because the method is a void. Is there anyway I can work around this problem?

Codesnippet from my controller:

 public IActionResult Edit(int? id)
        {
            if (id == 0 || id == 5)
            {
                return NotFound();
            }
            var model = new Inventory();
            model = repository.FindInventoryById(id); //This line doesn't work


            if (model == null)
            {
                return NotFound();
            }
            return View(model);
        }

Codesnippet from my repository:

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

public void FindInventoryById(int? id) 
        {
            db.Inventories.Find(id);
        }

>Solution :

You seem to be very confused by the basics of the language you’re using, which is fine we all start somewhere with programming, however I suggest you go back and read up on the basics of method calls, and returning values from methods.

For the sake of moving you along with this task you should make your method have a return type of Inventory and return it

public Inventory FindInventoryById(int? id) 
{
    return db.Inventories.Find(id);
}

And then your code works (you dont need to first create an empty Inventory though)

Inventory model = repository.FindInventoryById(id);
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