Hello, I just started to learn C #, I encountered such a problem.
It is necessary to initialize the array and its size from the keyboard, and then open access to it and its elements for another class.
Non-working code:
namespace ConsoleApplication1 { class MainClass { static void Main() { Massive instance = new Massive(); Console.WriteLine("Π Π°Π·ΠΌΠ΅Ρ ΠΌΠ°ΡΡΠΈΠ²Π°: "); instance.Size = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(instance.Size); instance.Input(); instance.Output(); Console.ReadKey(); } } class Massive { int i; int size = 0; int []mass = new int[size]; //ΠΈΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·Π°ΡΠΎΡ ΠΏΠΎΠ»Ρ Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ ΠΎΠ±ΡΠ°ΡΠ°ΡΡΡΡ ΠΊ Π½Π΅ΡΡΠ°ΡΠΈΡΠ΅ΡΠΊΠΎΠΌΡ ΠΏΠΎΠ»Ρ public int Size { set { size = value; } get { return size; } } public void Input() { for (i = 0; i < size; i++) { Console.WriteLine("ΠΠ²Π΅Π΄ΠΈΡΠ΅ ΡΠ»Π΅ΠΌΠ΅Π½Ρ ΠΌΠ°ΡΡΠΈΠ²Π°: "); mass[i] = Convert.ToInt32(Console.ReadLine()); } } public void Output() { for (i = 0; i < size; i++) { Console.Write(" "+mass[i]); } } } class Massive2 : Massive { //Π΄ΠΎΡΡΡΠΏ ΠΊ ΠΌΠ°ΡΡΠΈΠ²Ρ ΠΈ Π΅Π³ΠΎ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠ°ΠΌ Ρ ΠΊΠ»Π°ΡΡΠ° Massive } } Updated code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class MainClass { static void Main() { Massive instance = new Massive(); Console.WriteLine("Π Π°Π·ΠΌΠ΅Ρ ΠΌΠ°ΡΡΠΈΠ²Π°: "); instance.Size = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(instance.Size); instance.Input(); instance.Output(); Massive2 instance2 = new Massive2(); Console.WriteLine(); instance2.Method(); Console.ReadKey(); } } class Massive { int[] mass = null; int i; public int Size { set { if (value > 0) mass = new int[value]; else mass = null; } get { return (mass != null) ? mass.Length : 0; } } public int this[int index] { get { return mass[index]; } //ΠΎΡΠΈΠ±ΠΊΠ° Π·Π΄Π΅ΡΡ set { mass[index] = value; } } public void Input() { for (int i = 0; i < Size; i++) { Console.WriteLine("ΠΠ²Π΅Π΄ΠΈΡΠ΅ ΡΠ»Π΅ΠΌΠ΅Π½Ρ ΠΌΠ°ΡΡΠΈΠ²Π°: "); mass[i] = Convert.ToInt32(Console.ReadLine()); } } public void Output() { for (i = 0; i < Size; i++) { Console.Write(" " + mass[i]); } } } class Massive2 : Massive { public void Method() { //Π΄ΠΎΡΡΡΠΏ ΠΊ ΠΌΠ°ΡΡΠΈΠ²Ρ ΠΈ Π΅Π³ΠΎ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠ°ΠΌ Ρ ΠΊΠ»Π°ΡΡΠ° Massive int test = this[4]; Console.WriteLine(test); } } }
instance2is a completely different object, whereSizeis zero andmassis null. Add the lineinstance2.Size = 5;beforeinstance2.Method();- Igor