Alan Alan - 2 months ago 7
C# Question

Instantiate object inside another class not main method

Below I have created a simple class named 'Staff'. When I try to instantiate a new staff object in the main method, everything works perfect. Why does it work in the main method, but not in my farse method "Frog"?

class staff
{
//Fields
private string nameOfStaff;
private const int hourlyRate = 30;
private int hWorked;

//Properties
public int HoursWorked
{
get
{
return hWorked;
}
set
{
if (value > 0)
hWorked = value;
else
hWorked = 0;
}
}


//Methods
public void PrintMessage()
{
Console.WriteLine("Calculating Pay...");
}

public int CalculatePay()
{
PrintMessage();

int staffPay;
staffPay = hWorked * hourlyRate;

if (hWorked > 0)
return staffPay;
else
return 0;
}

public int CalculatePay(int bonus, int allowances)
{
PrintMessage();
if (hWorked > 0)
return hWorked * hourlyRate + bonus + allowances;
else
return 0;
}

public override string ToString()
{
return "Name of Staff = " + nameOfStaff + ", hourlyRate = " + hourlyRate + ", hWorked = " + hWorked;
}

//Constructors
public staff(string name)
{
nameOfStaff = name;
Console.WriteLine("\n" + nameOfStaff);
Console.WriteLine("-------------------------");
}

public staff(string firstName, string lastName)
{
nameOfStaff = firstName + " " + lastName;
Console.WriteLine("\n" + nameOfStaff);
Console.WriteLine("-------------------------");
}

}

class Program
{
static void Main(string[] args)
{
// Instanciating an Object
int pay;
staff staff1 = new staff("Peter");
staff1.HoursWorked = 160;
pay = staff1.CalculatePay(1000, 400);
Console.WriteLine("Pay = {0}", pay);
}

class frog

{
// Why can't I instantiate a staff member here?
}

Answer

You, probably, want to move the code from main into the frogs constructor, where you can access fields, methods, properties:

 class frog 
 {
   public staff Staff {get; set;} 

   public frog() {
     Staff = new staff("My Staff Name");

     // Now do everything you like with the Staff  
     Staff.HoursWorked = 123;  
   }  
 }