OOP Accessing data from a different method

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DGrund
    New Member
    • Jan 2017
    • 23

    OOP Accessing data from a different method

    I am a professional mainframe programmer, and I am trying to learn .Net. I have an OOO problem that is stumping me. I can get around it, but it would look like amateur hacking. I would like to do it the OOO way.

    Simply put:
    In one method (ReadAccounts), I am reading an Access table into a List (AcctsList). I don't have a problem with that; that works.
    In another method (DisplayAccount s), I would like to READ that list, and then process it.
    I tried to make the list "global", but I am tripping up on the language. Here is my code:
    Code:
    public void ReadAccounts()
    {
    var AcctsList = new List<AcctRec>(); // How do I make THIS AcctsList available to other programs?
    }
    
    public void DisplayAccounts()
    {
    // Process AcctsList from ReadAccounts above.
    }
    How do I do this? I'm sure there is a simple explanation to this.
    Thanks in advance! Any help is really appreciated.
    Dave
    Last edited by Niheel; Feb 1 '21, 01:01 AM. Reason: made the title more clear
  • Joseph Martell
    Recognized Expert New Member
    • Jan 2010
    • 198

    #2
    So you have a couple of options here. It partially depends on the context of what you are doing and where your code lives.

    Without more information, I would probably recommend changing the ReadAccounts method to return the accounts list:

    Code:
    public IEnumerable<AcctRec> ReadAccounts()
    {
         var AcctsList = new List<AcctRec>(); 
         //populate your account list
         return AcctsList;
    }
    
     public void DisplayAccounts()
    {
         var accounts = ReadAccounts();
         // do display stuff here.
    }
    This should address your immediate question.

    Comment

    • Arushi
      New Member
      • Oct 2022
      • 7

      #3
      The simplest solution would be to make the List a member variable of the class:

      Code:
      public class MyClass
      {
          private List<AcctRec> AcctsList = new List<AcctRec>();
       
          public void ReadAccounts()
          {
              // Read the accounts into the list
          }
       
          public void DisplayAccounts()
          {
              // Process the list
          }
      }

      Comment

      Working...