I was trying to make a program that would take person's name, age and what job he/she would like to work, and i have setted my job attribute in class as private, because i wanted to use get & set to get it back in return, but for some reason, i am only getting value as return, and nothing else:
using System;
namespace Exercise_Project
{
class Program
{
static void Main(string[] args)
{
//Apply for job application
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.Write("Enter how old are you: ");
int age = Convert.ToInt32(Console.ReadLine());
if (age < 18)
{
Console.WriteLine("You are too young to work!");
Console.ReadKey();
}
else
{
Console.Write("Which job would you like to work: Programmer, Magician, Baker - ");
string job = Console.ReadLine();
Employee Person = new Employee(name, age, job);
Console.WriteLine(Person.Job);
}
Console.ReadKey();
}
}
class Employee
{
public string name;
public int age;
private string job;
public Employee(string aName, int aAge, string aJob)
{
name = aName;
age = aAge;
job = aJob;
}
public string Job
{
get
{
return job;
}
set
{
if(value=="Programmer" || value== "Magician" || value == "Baker")
{
job = name ", welcome to your new job as " value;
}
else
{
job = name ", you don't have a job!";
}
}
}
}
}
CodePudding user response:
You never use the Job
setter. You only use the constructor and the getter:
Employee Person = new Employee(name, age, job);
Console.WriteLine(Person.Job);
You could use the setter before using the getter:
Employee Person = new Employee(name, age, job);
Person.Job = job;
Console.WriteLine(Person.Job);
Though that's a bit redundant after already using the constructor. You could also have the constructor internally use the setter:
public Employee(string aName, int aAge, string aJob)
{
name = aName;
age = aAge;
Job = aJob; // Note the use of Job instead of job
}