0

I'm trying to add data to 2D array and also assign to declared string (arr) if it's possible using C#. I'm new to C# and struggling already two days with this. Thank you in advance

    string[] arr = new string[] {};

    static string[,] ErrorList()
    {
        string[,] errs = {
            {"Err1","Text is too long"},
            {"Err2","Incorrect characters"},
        };

        if (FileChecker())
        {
           // I KNOW THIS IS ERROR BUT HERE I WANT TO ADD THIS LINE IF FILE(S) NOT FOUND
           // string[,] errs += {
           //  {"Err3","Txt file(s) was not found."},
           // };
         
        }
        
        // I KNOW THIS IS ERROR BUT I WANT TO ASSIGN errs to arr (declared string)    
        // TO REACH LATER FROM OTHER CLASSES     
        // arr = errs;

        return errs;
    }

    public static bool FileChecker()
    {
        DirectoryInfo d = new DirectoryInfo("template");
        FileInfo[] Files = d.GetFiles("*.txt");
       
        foreach (FileInfo file in Files)
        {
            Console.WriteLine(file.Name);
        }

        if(Files.Length != 0)
        {
            return true;
        }
        return false;
    }
Tiffany
  • 487
  • 2
  • 13
  • Thank you, I'll try and will answer your question – Tiffany Oct 07 '20 at 22:32
  • Yes, use a `List`, that is, a list of arrays of strings of size 2. Arrays can't be resized after they're created, but lists can. – O. Jones Oct 07 '20 at 22:39
  • 3
    That'll solve the immediate problem. Before you go too much farther, though, you should consider refactoring it to work with objects. For example, an `ErrorDetail` class with `Code` and `Description` properties would be much more semantically valuable, and much easier to work with, than an array of two strings. Then return a `List` from your method. – madreflection Oct 07 '20 at 22:46
  • Thank you for your answer, I will consider everything and post answer shortly if I will be able to solve this two problems. Thank you – Tiffany Oct 07 '20 at 23:00
  • 1
    @madreflection I agree completely. Learning to use Collection classes (List, Dictionary, HashSet and other IEnumerables) is worth the effort for experienced and inexperienced developers alike. The time you spend on that learning pays back many times over. Seriously. – O. Jones Oct 07 '20 at 23:13

1 Answers1

2

Ok I modified my code and now works good. Suggestions from O. Jones and madreflection helped me to understand what to do. I couldn't set this list globally but I'll find other way. Modified code:

static List<string> ErrorList()
    {
        List<string> ErrList = new List<string>();
        ErrList.Add("Text is too long");
        ErrList.Add("Invalid Characters");

        if (FileChecker())
        {
            ErrList.Add("File is missing");
        }
       
        return ErrList;
    }
Tiffany
  • 487
  • 2
  • 13