I'm learning c# and having some trouble understanding implementation of classes.
Below is a simple program i was writing to use classes. it takes your name and age, stores them in a class and displays them.
that code works fine.Code:// Namespace Declaration
using System;
public class CTest1
{
private string m_name;
private int m_age;
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public int Age
{
get { return m_age; }
set { m_age = value; }
}
}
public class CMain
{
public static void Main()
{
CTest1 aTest = new CTest1();
Console.WriteLine("Please Enter Name");
aTest.Name = Console.ReadLine();
Console.WriteLine("Please Enter Age");
aTest.Age = Int32.Parse(Console.ReadLine());
Console.Clear();
//CTest1 aTest = new CTest1();
Console.WriteLine("Your Name is: {0}", aTest.Name);
Console.WriteLine("You are: {0} years old.", aTest.Age);
}
}
so i split it up. i want individual methods to perform the input and out put so i split it up like this:
now I get 4 errors, one each where i've referenced my object 'aTest', the error is: 'aTest' does not exist in current context.Code:using System;
public class CTest1
{
private string m_name;
private int m_age;
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public int Age
{
get { return m_age; }
set { m_age = value; }
}
}
public class CMain
{
public static void Main()
{
CTest1 aTest = new CTest1();
CMain.getInput();
CMain.showOutput();
Console.ReadLine();
}
public static void getInput()
{
Console.WriteLine("Please Enter Name");
aTest.Name = Console.ReadLine();
Console.WriteLine("Please Enter Age");
aTest.Age = Int32.Parse(Console.ReadLine());
}
public static void showOutput()
{
Console.Clear();
Console.WriteLine("Your Name is: {0}", aTest.Name);
Console.WriteLine("You are: {0} years old.", aTest.Age);
}
}
how can i access my object from multiple methods. If i have to keep coming back to Main() to call the properties from my object it seems like it defeats the purpose of OOP.
I use VB .Net primarily, and once an object is initialized, as long as it's public, it is callable from all sub routines. Can someone help me make this connection please.

