Home > other >  Can't see array outside a public class
Can't see array outside a public class

Time:03-13

using System;
using System.Windows.Forms;

namespace arrays_1
{
    public partial class Form1 : Form
    {
        public string[] vettore; 

        public Form1()
        {
            InitializeComponent();
            vettore = new string[1];
        }

        public void btnImposta_Click()
        {
            ulong dimensione = Convert.ToUInt64(txtIndici.Text); 
            vettore = new string[dimensione];
        }

        public void btnInserisciAggiungi_Click()
        {
            btnInserisciAggiungi.Text = "Aggiungi";
            vettore[] = ["a", "b", "c"]; // CS0246
        }
    }
}

I edited the question, but the problem is still there. I'm trying to see the array named vettore created outside and used in 2 buttons. I'm getting Compiler Error CS0246 as an error, instead. Any type of help would be greatly appreciated.

CodePudding user response:

array1[] will not exist within the scope of btnSetAdd_Click().

Placing the variable outside of a method will allow you to access it from within other methods in the same class, like so:

namespace arrays_1
{
    public partial class Form1 : Form
    {
        public string[] array1; // defining a variable scoped to the class

        public Form1()
        {
            InitializeComponent();
            // initialize array to some valid size upon construction of the class
            array1 = new string[1];
        }

        public void btnSetSize_Click()
        {
            ulong arraySize = Convert.ToUInt64(txtSize.Text); 
            array1 = new string[arraySize]; // now you can resize the array
        }

        public void btnSetAdd_Click()
        {
            btnSet.Text = "Add";
            array1 = ["a", "b", "c"];
        }
    }
}

In this context, I would advise you to research some information regarding variable scopes, which is a fundamental piece of knowledge in programming.

CodePudding user response:

This line is incorrect

vettore[] = ["a", "b", "c"]; // CS0246

You don't need the square brackets, just the variable name. Like so;

vettore = ["a", "b", "c"];

You only need the brackets when you define an array;

public string[] vettore;
public int[] numbers;
  • Related