c# How to call a List from another Class

Viewed 179

I'm kinda new to c#, attempting to make a Phonebook Console App. Need some help figuring out how to call the list from another class. To understand my code: I've got a class (ContactsList) which contains the list. Then I've got another class (AppOptions) which has a few options the user can select, one being ViewAllContacts. So I need to know what code I need to write in the ViewAllContacts method, and if any other changes need to be made anywhere else.

public class ContactsList
    {
        public string contactName { get; set; }
        public int contactNumber { get; set; }

        public void listMethod()
        {
            List<ContactsList> contacts = new List<ContactsList>();
            {
                contacts.Add(new ContactsList { contactName = "John", contactNumber = 01 });
                contacts.Add(new ContactsList { contactName = "Jack", contactNumber = 02 });
                contacts.Add(new ContactsList { contactName = "Jay", contactNumber = 03 });
            }
        }
    }

 class AppOptions
    {
        ContactsList contactList = new ContactsList();
        public void viewAllContacts()
        {
           
        }
    }

Any extra improvement for my code would be really appreciated. Thanks!

EDIT: Another important thing I wanted was to loop through the list using the ViewAllContacts method

3 Answers

you should try the below code.

public class ContactsList
    {
        public string contactName { get; set; }
        public int contactNumber { get; set; }

        public IList<ContactsList> listMethod()
        {
            List<ContactsList> contacts = new List<ContactsList>();
            {
                contacts.Add(new ContactsList { contactName = "John", contactNumber = 01 });
                contacts.Add(new ContactsList { contactName = "Jack", contactNumber = 02 });
                contacts.Add(new ContactsList { contactName = "Jay", contactNumber = 03 });
            }

            return contacts;
        }
    }

    class AppOptions
    {
        ContactsList contactList = new ContactsList();
        public void viewAllContacts()
        {
            var lst = contactList.listMethod();
        }
    }
  • Contact which is a single contact (name and number)
  • Contacts which is a collection of Contacts

Here they are:

 public class Contact {
   public Contact(string name, string number) {
     if (null == name)
       throw new ArgumentNullException(nameof(name));
     if (null == number) 
       throw new ArgumentNullException(nameof(number));

     //TODO: Add more validation here

     Name = name;
     Number = number;   
   }

   public string Name {get;}
   // Let it be of type string: we can have numbers like "+1(555)123-45-67" 
   public string Number {get;}

   public override string ToString() => $"{Name} {Number}";

   public bool Equals(Contact other) {
     if (ReferenceEquals(this, other))
       return true;
     if (null == other)
       return false;

     return string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase) &&
            string.Equals(Number, other.Number, StringComparison.OrdinalIgnoreCase);
   }

   public override bool Equals(object obj) => obj is Contact other && Equals(other);

   public override int GetHashCode() => 
     Number?.GetHashCode(StringComparison.OrdinalIgnoreCase) ?? 0;
 }

The collection can be (if you prefer List<T>)

public class Contacts : IList<Contact> {
  private List<Contact> m_Items = new List<Contact>();

  public Contact this[int index] { 
    get => m_Items[index]; 
    set {
      if (null == value)
        RemoveAt(index);
      else
        m_Items[index] = value;
    } 
  }

  public void Add(Contact item) {
    if (null == item)
      throw new ArgumentNullException(nameof(item));

      m_Items.Add(item);
  }

  public void Insert(int index, Contact item) {
    if (null == item)
      throw new ArgumentNullException(nameof(item));

    m_Items.Insert(index, item);
  }

  public int Count => m_Items.Count;
  public bool IsReadOnly => false;
  public void Clear() => m_Items.Clear();
  public bool Contains(Contact item) => m_Items.Contains(item);
  public void CopyTo(Contact[] array, int arrayIndex) => m_Items.CopyTo(array, arrayIndex);
  public IEnumerator<Contact> GetEnumerator() => m_Items.GetEnumerator();
  public int IndexOf(Contact item) => m_Items.IndexOf(item);
  public bool Remove(Contact item) => m_Items.Remove(item);
  public void RemoveAt(int index) => m_Items.RemoveAt(index);
  IEnumerator IEnumerable.GetEnumerator() => m_Items.GetEnumerator();
}

then you can easily use it

private Contacts myContacts = new Contacts() {
  new Contact("John", "01"),
  new Contact("Jack", "02"),
  new Contact("Jay", "03"), 
};

...

public void viewAllContacts() {
  foreach (var contact in myContacts)
    Console.WriteLine(contact);           
}

First of all this is not good programming approach to declare a Class like this, you can create Class that will have properties contactName and contactNumber and then create another Class which will have listMethod. You should use this Class to fetch the data.

Anyway in this scenario you just need to change the Return type of listMethod, it is void right now so not returning anything and also you can loop through contacts using foreach loop.

public class ContactsList
    {
        public string contactName { get; set; }
        public int contactNumber { get; set; }

        public List<ContactsList> listMethod()
        {
            List<ContactsList> contacts = new List<ContactsList>();
            {
                contacts.Add(new ContactsList { contactName = "John", contactNumber = 01 });
                contacts.Add(new ContactsList { contactName = "Jack", contactNumber = 02 });
                contacts.Add(new ContactsList { contactName = "Jay", contactNumber = 03 });
            }
        }
    }

 class AppOptions
    {
        ContactsList contactList = new ContactsList();
        public void viewAllContacts()
        {
           var contacts = contactList.listMethod();
           foreach(var item in contacts)
           {
               Console.WriteLine(item.contactName);
               Console.WriteLine(item.contactNumber);
           }
        }
    }
Related