Error accessing string array

William O'Gorm 61 Reputation points
2020-08-27T19:59:42.323+00:00

Hello. I can initialize the array just fine, but when I try to access it, I get an error: "the name does not exist in the current context" I copy/paste code from the internet and it is still doing this. I tried changing all the different combinations of public and private, and it still happens. Thanks in advance!

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,517 questions
{count} votes

3 answers

Sort by: Most helpful
  1. William O'Gorm 61 Reputation points
    2020-08-27T22:20:42.637+00:00

    The error is on the line that starts with "test":

    namespace DM
    {
    class Armour
    {

        string[] strArray = new string[] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
    
        string test;
    
        test = strArray[0]; 
    
    0 comments No comments

  2. Dylan Zhu-MSFT 6,401 Reputation points
    2020-08-28T02:19:31.807+00:00

    Hi WilliamOGorm,

    The "test" should be placed in a function, not directly inside a class. You could update your code like this:

    namespace DM
    {
    #include <cstring>
    #include <iostream>
    
        class Armour
        {
        public:
            string strArray[5] = { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
            string test;
    
            string test() {
                test = strArray[0];
                return test;
            }
        };
    };
    

    Best Regards,
    Dylan

    0 comments No comments

  3. RLWA32 39,451 Reputation points
    2020-08-28T10:04:30.417+00:00

    In appears you are coding in C#. So consider the following:

    namespace DM
    {
            class Armour
            {
                string[] strArray = new string[] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
                string test;
    
                static string[] staticArray = new string[] { "Tom", "Dick", "Harry" };
                string test2 = staticArray[0];  // initialize from static array
    
                public string Test1()
                {
                    test = strArray[0];
                    return test;
                }
    
    0 comments No comments