I get an error when run the console app since obviously instance of P doesnt exist. What I cant understand is where should be "newing" it? Should it be in the constructor of Employee (that didnt work when I tried) ??
public class Person
{
private string name;
public string Name // read-write instance property
{
get
{
return name;
}
set
{
name = value;
}
}
}
interface IEmployee
{
Person P
{
get;
set;
}
int Counter
{
get;
}
}
public class Employee : IEmployee
{
private Person p;
public static int numberOfEmployees;
public Person P // read-write instance property
{
get
{
return p;
}
set
{
p = value;
}
}
private int counter;
public int Counter // read-only instance property
{
get
{
return counter;
}
}
public Employee() // constructor
{
counter = ++counter + numberOfEmployees;
}
}
class Program
{
static void Main(string[] args)
{
System.Console.Write("Enter number of employees: ");
Employee.numberOfEmployees = int.Parse(System.Console.ReadLine());
Employee e1 = new Employee();
System.Console.Write("Enter the name of the new employee: ");
e1.P.Name = System.Console.ReadLine();
System.Console.WriteLine("The employee information:");
System.Console.WriteLine("Employee number: {0}", e1.Counter);
System.Console.WriteLine("Employee name: {0}", e1.P.Name);
Console.ReadLine();
}
}
Yes, somewhere in your program you are missing the line
e1.P = new Person();
Either right in front of reading the name, or maybe in the constructor of Employee.
If you modify your code like this, it will work
class Program
{
static void Main(string[] args)
{
System.Console.Write("Enter number of employees: ");
Employee.numberOfEmployees = int.Parse(System.Console.ReadLine());
Employee e1 = new Employee();
e.P = new Person(); //add this line
System.Console.Write("Enter the name of the new employee: ");
e1.P.Name = System.Console.ReadLine();
System.Console.WriteLine("The employee information:");
System.Console.WriteLine("Employee number: {0}", e1.Counter);
System.Console.WriteLine("Employee name: {0}", e1.P.Name);
Console.ReadLine();
}
}
Related
I am working in a C# console application and I am learning OOP.
First, I have a Person Class,
class Person
{
public string Name;
public string LastName;
public void Comment()
{
Console.WriteLine("Comment from Person Class");
}
and Student class
class Student : Person
{
public int IndexNr = 171124;
public int totalSubjects;
public Student()
{
Console.WriteLine("Index number=" + IndexNr);
}
public Student(int subjectsTotal,int nr)
{
totalSubjects= nr;
Console.WriteLine("Average grade= " + subjectsTotal/ totalSubjects);
}
public void Comment()
{
Console.WriteLine("Comment from Student class");
}
}
And in the Program.cs in the Main function the code goes like this:
static void Main(string[] args)
{
Console.WriteLine("Student Info");
Student st2= new Student();
st2.Name= "name1";
st2.LastName = "lastname1";
Console.WriteLine("Name=" + st2.Name+ " LastName=" + st2.LastName);
Student st1 = new Student(90,10);
//Polymorphism example -> here is where I need help
Person p1 = new Person();
Person s1 = new Student();
p1.Komenti();
s1.Komenti();
}
So, when I create Person s1 = new Student() object it prints out the the Comment function from only Person class, and not 1 from Person and 1 from Student class.
I have tried the same in Java as well and there it works very well.
Can you please tell me and enlighten me where am I making mistakes or what am I missing?
Thank you.
Try using the override modifier on the Comment method in the Student class https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/override This should then override the person implementation
public class Student : Person
{
public int IndexNr = 171124;
public int totalSubjects;
public Student()
{
Console.WriteLine("Index number=" + IndexNr);
}
public Student(int subjectsTotal,int nr)
{
totalSubjects= nr;
Console.WriteLine("Average grade= " + subjectsTotal/ totalSubjects);
}
public override void Comment()
{
Console.WriteLine("Comment from Student class");
}
}
Hi am new to OOP and I am doing a task right now however I cant link the customer class and objects into my main program. It says that it doesn't exist in the current context. This maybe also due to me not understanding the name spaces completely and may have the names of the class in the file directory being incorrect but if I am honest I don't know.
Main program (file direct name is MainProg)
class Program
{
static void Main(string[] args)
{
//New Customer Account Sequence
//Customer customerOne = new Customer();
Console.WriteLine("Customer Details:\n-----------------\n");
Console.Write("Please enter cutomer forename: ");
customerOne.Forename = Console.ReadLine();
customerOne.Surname = Console.ReadLine();
customerOne.Address = Console.ReadLine();
customerOne.Town = Console.ReadLine();
customerOne.Postcode = Console.ReadLine();
CurrentAccount accountCurrOne = new CurrentAccount();
//accountCurrOne.AccountNumber = 1000;
SavingsAccount accountSavOne = new SavingsAccount();
accountSavOne.AccountNumber = 1001;
accountCurrOne.Open(customerOne);
accountSavOne.Open(customerOne);
//Initial deposit
decimal depositAmount;
depositAmount = decimal.Parse(Utility.Console.Ask("Enter initial deposit: "));
accountCurrOne.Deposit(depositAmount);
accountSavOne.Deposit(depositAmount);
// End of New Customer Account Sequence
Console.ReadLine();
}
}
Customer Class (Name in file directory is CustomerOne)
class CustomerOne : BankAccount
{
protected string _Forename;
protected string _Surname;
protected string _Address;
protected string _Town;
protected string _Postcode;
public string Forename
{
get { return _Forename; }
set { Forename = value; }
}
public string Surname
{
get { return _Surname; }
set { Surname = value; }
}
public string Address
{
get { return _Address; }
set { Address = value; }
}
public string Town
{
get { return _Town; }
set { Town = value; }
}
public string Postcode
{
get { return _Postcode; }
set { Postcode = value; }
}
}
Can someone tell me where I am messing up?
In order to call properties and methods of an object, you must instantiate it.
The problem is the following line that you commented:
//Customer customerOne = new Customer();
This line creates a new instance of the Customer class. Once you create an instance with the keyword new and assigned it to a variable, you can call class methods and properties with variable.Property or variable.Method().
This applies for classes that are not Static.
A reference for instances: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/objects
I'm trying to return multiple parameters, if that's how to word it. I'm trying to "translate" Python code into C#.
I'm actually not quite sure what exact term I'm searching for, but I know how to do it in Python so I'll just show my code.
class Staff
{
public String name;
public int age;
/* Now in Python, you can easily write this following, but I have no
idea how this works in C#. I basically want to return all the values
for each employee in the "Staff" class */
def desc(self):
desc_str = "%s is %s years old." % (self.name, self.age)
return desc_str
}
class Program
{
public static void Main()
{
Staff Jack = new Staff();
Jack.name = "Jack";
Jack.age = 40;
Staff Jill = new Staff();
Jill.name = "Jill";
Jill.age = 50;
Console.WriteLine(Jack.desc());
Console.WriteLine(Jill.desc());
Console.ReadKey();
}
}
EDIT: I figured out that what I was searching for was get, set and ToString() and will look into it now.
The code I've translated looks like the following now:
class Staff
{
private string name;
private int age;
private string yearsold = " years old.";
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string YearsOld
{
get
{
return yearsold;
}
set
{
yearsold = value;
}
}
public override string ToString()
{
return "Employee " + Name + " is " + Age + YearsOld;
}
}
class TestPerson
{
static void Main()
{
// Create a new Person object:
Staff person = new Staff();
person.Name = "Jack";
person.Age = 40;
Console.WriteLine(person);
person.Name = "Jill";
person.Age = 50;
Console.WriteLine(person);
Console.ReadKey();
}
}
Since you have a class, you can override the ToString function and use the string.Format function like so:
class Staff
{
public string name;
public int age;
public Staff(string _name, int _age)
{
this.name = _name;
this.age = _age;
}
public override string ToString()
{
return string.Format("{0} is {1} years old.", this.name, this.age);
}
}
Then to print:
Staff Jack = new Staff("Jack", 40);
Console.WriteLine(Jack); // implicitly calls Jack.ToString()
Hope that helps.
I have a simple program with with an employee class and i have 2 objects in this class lynda and alex, I have also created a method called CalculateTotalPay() which prints the total pay to the console after a simple addition of the salary and bonus. Right now the for the print to console I have Console.WriteLine("Total Pay = " + totalPay); but I want to make it into
Console.WriteLine("Total Pay for " + employeeName " = " + totalPay); but I dont want to repeatedly assing new employees to new variables, what would be the best way to do this ?
Here is the Code
class Employee
{
public double salary;
public double bonus;
public string employeeName;
public void CalculateTotalPay()
{
double totalPay = salary + bonus;
Console.WriteLine("Total Pay = " + totalPay);
}
}
static void Main()
{
Employee alex = new Employee();
Employee lynda = new Employee();
alex.salary = 900000;
alex.bonus = 20000;
alex.CalculateTotalPay();
lynda.salary = 100000;
lynda.bonus = 20000;
lynda.CalculateTotalPay();
}
First, your class should look like this:
class Employee
{
public double Salary { get; set; }
public double Bonus { get; set; }
public string Name { get; set; }
public Employee(String name, double salary, double bonus)
{
Salary = salary;
Bonus = bonus;
Name = name;
}
public void CalculateTotalPay()
{
double totalPay = Salary + Bonus;
Console.WriteLine("Total Pay for {0} = {1}", Name, totalPay);
}
}
Now you can simply use the constructor:
Employee alex = new Employee("alex", 900000, 20000);
Employee lynda = new Employee("lynda", 100000, 20000);
Edit: Apparently your problem is a bit different.
If you have no external source of information you have to define all employees inside the code. I would recommend this way:
List<Employee> Employees = new List<Employee>
{
new Employee("alex", 900000, 20000),
new Employee("lynda", 100000, 20000)
};
foreach (var employee in Employees) {
employee.CalculateTotalPay();
}
For the sake of readability, do it this way and don't start to make like 3 seperate arrays for bonuses, salaries and names.
You can use List<Employee> workers = new List<Employee>();.
Add new Employee is easy - workers.Add( new Employee {salary = 10, bonus = 100});.
And finally you can interate over this collection:
foreach (var item in workers)
{
//TODO
}
I think you were looking for below solution.
class Program
{
static void Main(string[] args)
{
IEnumerable<Employee> employees = new List<Employee>
{
new Employee("Alex", 900000, 20000),
new Employee("Lynda", 100000, 20000)
};
foreach (var employee in employees)
{
employee.CalculatePay();
}
Console.ReadKey();
}
}
public class Employee
{
private readonly double _salary;
private readonly double _bonus;
private readonly string _name;
public double Salary { get { return _salary; } }
public double Bonus { get { return _bonus; } }
public string Name { get { return _name; } }
public Employee(string name, double salary, double bonus)
{
_name = name;
_salary = salary;
_bonus = bonus;
}
public void CalculatePay()
{
double totalPay = Salary + Bonus;
Console.WriteLine("Total Pay for Employee {0} = {1}", Name, totalPay);
}
}
I'm trying to figure out how to populate an array with an object with multiple variables. What I need is to create an array, not a list(I'm trying to learn arrays), and populate it with 5 different bourbons. Is it possible to populate the array and store the name, age, distillery in just one index? For example,
If I called index 0, it would display:
Name: Black Maple Hill
Distillery: CVI Brands, Inc
Age: 8 years
I have this so far, in which bourbon is a derived class from whiskey and call a method in the main class to prompt user for entry.
class Bourbon : Whiskey
{
private Bourbon[] bBottles = new Bourbon[5];
public void bourbon(string name, string distillery, int age)
{
Name = name;
Distillery = distillery;
Age = age;
}
public void PopulateBottles()
{
Console.WriteLine("Please enter the information for 5 bourbons:");
for (int runs = 0; runs < 5; runs ++)
{
}
}
}
In your code you haven't defined the value variable that you are using inside the for loop. You could create new instances of the class and then store them inside the array:
public void PopulateBottles()
{
Console.WriteLine("Please enter the information for 5 bourbons:");
for (int runs = 0; runs < 5; runs ++)
{
Console.WriteLine("Name:");
var name = Console.ReadLine();
Console.WriteLine("Distillery:");
var distillery = Console.ReadLine();
Console.WriteLine("Age:");
var age = int.Parse(Console.ReadLine());
var bourbon = new Bourbon(name, distillery, age);
bBottles[runs] = bourbon;
}
}
Also make sure you have defined the Bourbon class constructor properly:
public Bourbon(string name, string distillery, int age)
{
Name = name;
Distillery = distillery;
Age = age;
}
#Jonathan. Yes, it is possible, based on my interpretation. You can try making use of indexers.
Class Bourbon : Whiskey {
public Bourbon this[int index]
{
get {
return bBottles[index];
}
set {
bBottles[index] = value;
}
}
}
Check this Need to Create Property and One Constructor to achieve your requirement.
class Bourbon
{
private Bourbon[] bBottles = new Bourbon[5];
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string distillery;
public string Distillery
{
get { return distillery; }
set { distillery = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public Bourbon(string name, string distillery, int age)
{
Name = name;
Distillery = distillery;
Age = age;
}
public void PopulateBottles()
{
Console.WriteLine("Please enter the information for 5 bourbons:");
for (int runs = 0; runs < 5; runs++)
{
Console.WriteLine("Name:");
var name = Console.ReadLine();
Console.WriteLine("Distillery:");
var distillery = Console.ReadLine();
Console.WriteLine("Age:");
var age = int.Parse(Console.ReadLine());
var bourbon = new Bourbon(name, distillery, age);
bBottles[runs] = bourbon;
}
}
}