shw shw - 1 year ago 64
C# Question

How can I prevent the function from being called if the property is already set?

I have a function that sets 2 lists within a class to pull from a third party.

I put it in one function because going to the third party takes time and I only want to have to do it once for this page.
This is my class:

public class MyClass
public IEnumerable<dynamic> ListOne { get; set; }
public IEnumerable<dynamic> ListTwo { get; set; }

This is my function that sets & returns the lists

public MyClass GetLists()
//Here I have the code that connects to the third party etc
//Here set the items.. from the third party
MyClass _MyClass = new MyClass();
_MyClass.ListOne = ThirdParty.ListOne;
_MyClass.ListTwo = ThirdParty.ListTwo;
return (_MyClass);

So, now in my web API I have 2 functions - one that returns each list.

public IHttpActionResult GetListOne()
IEnumerable<dynamic> ListOne = GetLists().ListOne;
return Json(ListOne);

public IHttpActionResult GetListTwo()
IEnumerable<dynamic> ListTwo = GetLists().ListTwo;
return Json(ListTwo);

My problem is that each time I call the webApi getListone or getListTwo, the function will run again and call the third party. How can I prevent this?

Thank you!

Answer Source

Put the data retrieving logic in the property and lazy-load the data, i.e. load it the first time the property is called.

private IEnumerable<dynamic> _listOne;
public IEnumerable<dynamic> ListOne {
    get {
        if (_listOne == null) {
            // Retrieve the data here. Of course you can just call a method of a
            // more complex logic that you have implemented somewhere else here.
            _listOne = ThirdParty.ListOne ?? Enumerable.Empty<T>();
        return _listOne;

?? Enumerable.Empty<T>() ensures that null will never be returned. Instead an empty enumeration will be returned.

See: ?? Operator (C# Reference) and
        Enumerable.Empty Method ()

Have also a look at the Lazy<T> Class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download