0

I am trying to read a list of contacts from a CSV file into a list.

My code below reads the file, and creates the list; however I am having problems accessing the elements from the list, ie values.Email etc...

namespace Contacts
{
    public partial class Form1 : Form
    {
    public Form1()
        {
            InitializeComponent();
            ReadContacts();
        }

        static void ReadContacts()
        {
        List<Contacts> values = File.ReadAllLines("D:\\Contacts.csv")
                                    .Skip(1)
                                    .Select(v => Contacts.FromCsv(v))
                                    .ToList();

       Debug.WriteLine(values[0].Email);
        }
    }

    class Contacts
    {
        string First;
        string Last;
        string Email;

        public static Contacts FromCsv(string csvLine)
        {
            string[] values = csvLine.Split(',');
            Contacts contacts = new Contacts();

            contacts.First = values[0];
            contacts.Last  = values[1];
            contacts.Email = values[2];

            return contacts;
        }
    }
}

Watch window shows the list read Watch Window

David Makogon
  • 69,407
  • 21
  • 141
  • 189
rams59
  • 23
  • 6
  • It's not clear what problem you face or what you consider "wrong". Can you provide more detail or better description? – Jasen May 19 '23 at 19:41
  • It's not as if they're declared as public, so non-public would be the expected behaviour. – Chris Cudmore May 19 '23 at 19:44
  • 1
    Does this answer your question? [What are the default access modifiers in C#?](https://stackoverflow.com/questions/2521459/what-are-the-default-access-modifiers-in-c). See also: [Access Modifiers](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers) – 001 May 19 '23 at 19:46

1 Answers1

2

The problem I encountered when I entered your code in .NET Fiddle is that fields in Contacts class are not public, hence are inaccessible from outside the class.

I'd recommend rewriting the class as

class Contacts
{
    public string First { get; init; }
    public string Last { get; init; }
    public string Email { get; init; }

    public static Contacts FromCsv(string csvLine)
    {
        string[] values = csvLine.Split(',');
        Contacts contacts = new Contacts()
        {
            First = values[0],
            Last  = values[1],
            Email = values[2]
        };
        return contacts;
    }
}
orhtej2
  • 2,133
  • 3
  • 16
  • 26