Hi
following my previous question, i added a non-static method to the code, but now i can't access it from Main:
I get two errors at bold lines (myObj does not exist ...)
Thanks
using System;
class Stm
{
string name;
static void Main(string[] args)
{
Stm[] myObj = new Stm[3];
for (int i = 0; i < myObj.Length; i++)
myObj[i] = new Stm();
myObj[0].naam = "Macron";
myObj[1].naam = "Biden";
myObj[2].naam = "Sunak";
myObj.show();
}
void show()
{
for (int i = 0; i < myObj.Length; i++)
Console.WriteLine(name);
}
}
Sachin SinghPosted Jan 22, 2023, 6:21 AM
Pasang TamangPosted Jan 22, 2023, 1:53 AM
Hi,
Problem in your code is you are trying to access myObj in show method but declaration of myObj is in Main. myObj in show method cannot be access as it is out of scope. You can use parameter in show method like void show(Stm[] myObj). And to access non static field inside static method, you have to initialize your class first. Below code example I prepared for your reference.
Regards,
Pasang