C# Base class constructor arguments - c#

I learning C#. I want to see what is the best way to implement inheritance. I have a Employee base class and a PartTime derived class. Employee class only receives First and Last name and has a method to print full name.
I want to know what is the proper way to pass First and last name so that when I just call PartTime class I should be also able to print full name from the calling program. At the moment it is showing blank as full name:
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee("John", "Doe");
// emp.PrintFullName();
PartTime pt = new PartTime();
float pay=pt.CalcPay(10, 8);
pt.PrintFullName();
Console.WriteLine("Pay {0}", pay);
Console.ReadKey();
}
}
public class Employee
{
string _firstName;
string _last_name;
public Employee(string FName, string LName)
{
_firstName = FName;
_last_name = LName;
}
public Employee() { }
public void PrintFullName()
{
Console.WriteLine("Full Name {0} {1} ", _firstName, _last_name);
}
}
public class PartTime : Employee
{
public float CalcPay(int hours, int rate)
{
return hours * rate;
}
}

You can call the base class constructor from you derived class like this:
public class PartTime : Employee
{
public PartTime(string FName, string Lname)
: base(FName, LName)
{ }
}
and then create it,
PartTime pt = new PartTime("Part", "Time");

Try this:
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Employee(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
//method implementations removed for clarity
}
public class PartTime:Employee
{
public PartTime(string firstName, string lastName)
: base(firstName, lastName)
{
}
}
Note that your base constructor will run before any code in your derived constructor, should you need further initialization logic in the PartTime class.

You want to add a constructor to PartTime that will pass along the first and last name to the base constructor
public PartTime(string fName, string lName) : base(fName, lName) {
}
Or you could make first and last name public properties on Employee which would be inherited by PartTime. Then you can initialize them when creating instances of either without having to maintain the PartTime constructor.
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee { FirstName = "John", LastName = "Doe" };
emp.PrintFullName();
PartTime pt = new PartTime { FirstName = "Jane", LastName = "Doe" };
float pay=pt.CalcPay(10, 8);
pt.PrintFullName();
Console.WriteLine("Pay {0}", pay);
Console.ReadKey();
}
}
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public void PrintFullName()
{
Console.WriteLine("Full Name {0} {1} ", FirstName, LastName);
}
}
public class PartTime : Employee
{
public float CalcPay(int hours, int rate)
{
return hours * rate;
}
}

Related

Realising of the function

Can anybody please tell me, how to realise my function in main body ?
All works, but i want to do a catalog of employers, so how to write employe to list or massive?
class Catalog : Employe
{
Employe[] employes = new Employe[10];
Employe p1 = new Employe(14, "Mark", "James", 124151, "Coder", 4000);
public Catalog(int _age, string _firstName, string _lastName, int _id, string _job, int _salary) : base(_age, _firstName, _lastName, _id, _job, _salary)
{
employes[1] = p1;
}
public void CatalogLog()
{
for(int i = 0; i < employes.Length; i++)
Console.WriteLine(employes[i]);
}
}
class TestInheritence
{
public static void Main(string[] args)
{
Employe[] employes = new Employe[10];
}
}
I think you didn't set up the inheritance hierarchy with the right logic. The base class Employee is extensible and contains base methods:
public class Employee
{
private int _id;
private string _firstName;
public Employee(int id, string firstName)
{
_id = id;
_firstName = firstName;
}
public int GetID()
{
return _id;
}
public void SetID(int id)
{
if(id > 0)
_id = id;
}
public void Print()
{
Console.WriteLine("ID: {0}\tFirst Name: {1}", this._id, this._firstName);
}
}
The derived class allows the object to expand by adding new methods and properties to the properties of the base class:
public class Manager : Employee
{
private string _city;
public Manager(int id, string firstName, string city) : base(id, firstName)
{
_city = city;
}
public string GetCity()
{
return _city;
}
}
To test how these two classes work, you can review the application code below:
public class Program
{
public static void Main()
{
Employee[] employees = new[]
{
new Employee(1, "Thomas"),
new Employee(2, "John"),
new Employee(3, "Erick"),
new Employee(4, "Ahmet"),
new Employee(5, "Sun")
};
employees[0].Print();
Manager manager = new Manager(6, "Johnson", "London");
manager.Print();
Console.WriteLine("City: {0}", manager.GetCity());
}
}
If you want to add the employees to the catalog you can have an 'add' function that will add the employee to the catalog:
class Catalog : Employe
{
List<Employe> employes = new List<Employe>();
public void AddEmployee(int _age, string _firstName, string _lastName, int _id, string _job, int _salary) : base(_age, _firstName, _lastName, _id, _job, _salary)
{
Employe p1 = new Employe(_age, _firstName, _lastName, _id, _job, _salary);
employes.Add(p1);
}
public void CatalogLog()
{
for(int i = 0; i < employes.Count(); i++)
Console.WriteLine(employes[i]);
}
}
class TestInheritence
{
public static void Main(string[] args)
{
Catalog catalog = new Catalog();
catalog.AddEmployee(14, "Mark", "James", 124151, "Coder", 4000);
// Add more employees.
}
}
But I think that this is the wrong use case for inheritance. Usually you want to inherit when there is a 'Is-a' relationship between the types. But 'Catalog' is not type of 'Employee'

How to pass a string from Class 1 to Class 2 to Class 3?

I have 3 classes (UCourse, Student and Teacher) and each class has a unique string property.
Is there a simple way I can take the string property from the first class UCourse, pass it into a 2nd class Student, and then pass that string plus another string from the 2nd class into a 3rd class Teacher?
This is what I have so far for my 3 classes:
using System;
namespace EDXonline_AssignmentFour
{
class Program
{
class UCourse
{
// Set the unique string for the 1st class
private string course = "Computer Scienece";
public string Course
{
get { return course; }
}
}
class Student
{
// Get the string from the 1st class
UCourse ucourse = new UCourse();
public string coursef1
{
get { return ucourse.Course; }
}
// Set the unique string for the 2nd class
private string name = "zach";
public string Name
{
get { return name; }
}
}
class Teacher
{
Student student = new Student();
private string namet = "Sally";
// Get the unique string from the 2nd class
public string namef1
{
get { return student.Name; }
}
// Set the unique string for the 3rd class
public string Namet
{
get { return namet; }
}
}
}
}
Then, I need to create an instance of Teacher and by using only this instance of Teacher, I need to output all string properties from each of the 3 classes like this:
public static void Main (string [] args)
{
Teacher teacher = new Teacher();
Console.WriteLine("{0} and {1} are in {2}",
teacher.namef1, teacher.Namet /*, UCourse string from the 1st class goes here*/);
}
So far that works to display the strings from the 2nd and 3rd classes, but how can I get the value of the UCourse string from the first class as well?
If you want to use your existing code and keep passing the strings through properties, then you almost solved it because your Main() method already shows the correct values of the strings from the 2nd and 3rd classes.
To access the string from the 1st class and use it in the 3rd class, you can add another property to the 3rd class to get it (same as you already did to get the string from the 2nd class).
For example:
class Teacher
{
Student student = new Student();
// Get the unique string from the 2nd class
public string namef1
{
get { return student.Name; }
}
// Get the unique string from the 1st class that's already stored in the 2nd class
public string UCourseName
{
get { return student.coursef1; }
}
// Set the string for the third class
private string namet = "Sally";
public string Namet
{
get { return namet; }
}
}
And then you can update your Main() method to use it like this:
public static void Main(string[] args)
{
Teacher teacher = new Teacher();
// Writes "Zach and Sally are in Computer Science"
Console.WriteLine("{0} and {1} are in {2}",
teacher.namef1, teacher.Namet, teacher.UCourseName);
Console.ReadLine();
}
that would be :
internal class Program
{
private static void Main( string[] args )
{
Teacher teacher = new Teacher();
Console.WriteLine("{0} and {1} are in {2}",
teacher.Namef1, teacher.Namet, teacher.Course);
}
private class UCourse
{
// Set the unique string for the 1st class
private readonly string course = "Computer Scienece";
public string Course { get { return this.course; } }
}
private class Student
{
// Set the unique string for the 2nd class
private readonly string _name = "zach";
public string Name { get { return this._name; } }
// Get the string from the 1st class
private readonly UCourse _ucourse = new UCourse( );
public string Coursef1 { get { return this._ucourse.Course; } }
}
private class Teacher
{
private readonly Student _student = new Student( );
// Get the unique string from the 1nd class
public string Course { get { return this._student.Coursef1; } }
// Get the unique string from the 2nd class
public string Namef1 { get { return this._student.Name; } }
// Set the unique string for the 3rd class
private readonly string _namet = "Sally";
public string Namet { get { return this._namet; } }
}
}
I recommend that you rethink your classes. Here is a small example:
using System;
using System.Collections.Generic;
namespace Example
{
public class Course
{
public string CourseTitle { get; set; }
public List<Student> Students { get; set; }
public Course(string courseTitle)
{
CourseTitle = courseTitle;
Students = new List<Student>();
}
}
public class Student
{
public string Name { get; set; }
public Student(string name)
{
Name = name;
}
}
public class Teacher
{
public string Name { get; set; }
public List<Course> Courses { get; set; }
public Teacher(string name)
{
Name = name;
Courses = new List<Course>();
}
}
class Program
{
static void Main(string[] args)
{
List<Teacher> teachers = new List<Teacher>();
Course course1 = new Course("Astrophysics A");
Course course2 = new Course("Coding C#");
Student student1 = new Student("Peter");
Student student2 = new Student("Bill");
Student student3 = new Student("Anna");
Teacher teacher1 = new Teacher("Mr. Williams");
Teacher teacher2 = new Teacher("Mr. Jacobson");
course1.Students.Add(student1);
course1.Students.Add(student3);
course2.Students.Add(student2);
teacher1.Courses.Add(course1);
teacher2.Courses.Add(course2);
teachers.Add(teacher1);
teachers.Add(teacher2);
foreach (Teacher teacher in teachers)
{
foreach (Course course in teacher.Courses)
{
foreach (Student student in course.Students)
{
Console.WriteLine("{0} and {1} are in {2}", student.Name, teacher.Name, course.CourseTitle);
}
}
}
Console.ReadLine();
}
}
}
I guess this way provides you more flexibility, in your code only 1 to 1 connections are possible.
Hope this was helpful.

Calling method inside a method in Interface c#

How to call a method inside a method in same class when using interface in c#? I got error when tried access through (object as baseclass).method
interface IAccount
{
string fullName{get;set;}
void Balance();
}
public class User : IAccount
{
public string fullName { get; set; }
public int balance = 10000;
public User(string firstName, string lastName)
{
fullName = firstName + lastName;
}
public void IAccount.Balance()
{
Console.WriteLine("Account balance-" + this.balance);
}
public void MyBalance()
{
Console.WriteLine(" My balance");
IAccount.Balance();
}
}
Try to remove the both IAccounton from public void Balance() and inside public void MyBalance()
interface IAccount
{
string fullName{get;set;}
void Balance();
}
public class User : IAccount
{
public string fullName { get; set; }
public int balance = 10000;
public User(string firstName, string lastName)
{
fullName = firstName + lastName;
}
public void Balance()
{
Console.WriteLine("Account balance-" + this.balance);
}
public void MyBalance()
{
Console.WriteLine(" My balance");
Balance();
}
}
Output:
Account balance-10000
My balance
Account balance-10000
When you create a method which is named InternfaceName.MethodName it is called Explicit interface implementation.
What it means is that that method is accessible only through a reference of the interface type.
So... How can you call to that method from within the class? Cast this to the interface type!
public void MyBalance()
{
Console.WriteLine(" My balance");
((IAccount)this).Balance();
}

Does not contain a constructor that takes 2 arguments?

I am currently doing some class coding and wonder what went wrong with my project?
class ContactPerson
{
string name;
ContactNo telNo;
public ContactPerson(string in_Name, ContactNo in_No)
{
name = in_Name;
telNo = new ContactNo();
}
public string getName()
{
return name;
}
public ContactNo getContactInfo()
{
return telNo;
}
public void setName(string in_Name)
{
name = in_Name;
}
public void setContactInfo (ContactNo in_No)
{
telNo = in_No;
}
}
}
class ContactNo
{
string contactType;
string contactNo;
public void setContactType(string in_Type)
{
contactType = in_Type;
}
public string getContactType()
{
return contactType;
}
public void setContactNo(string in_No)
{
contactNo = in_No;
}
public string getContactNo()
{
return contactNo;
}
}
}
class Program
{
static void Main(string[] args)
{
ContactNo telNo;
telNo = new ContactNo("Mobile No: ", 95656565);
ContactPerson myFriend;
myFriend = new ContactPerson("Fred Smith", telNo);
string strName;
strName = myFriend.getName();
Console.WriteLine(" " + strName);
ContactNo outContact;
outContact = myFriend.getContactInfo();
outContact.getContactType();
Console.WriteLine(outContact);
outContact.getContactNo();
Console.WriteLine(outContact);
Console.ReadLine();
}
}
}
At the program class
" telNo = new ContactNo("Mobile No: ", 95656565); "
theres error saying Does not contain a constructor that takes 2 arguments
may i know why?
That would be because you don't have a constructor that contains two arguments in the ContactNo class, as the error suggests. Take a look in the class, and you'll notice that there is no constructor there. You DO have one in the ContactPerson class, though.
This line: telNo = new ContactNo("Mobile No: ", 95656565);
is calling a constructor for ContactNo that takes two arguments: a string, and an int. You don't have a constructor that is set up to do this currently, and that's where your error is. You could create one by adding
public ContactNo(string s, int n){
//initializations
}
or something of that nature. Or, if you're using a string for the number (which it looks like), replace int n with string s2 or whatever you wish to call it.
because you dont have contact no constructor with 2 parameters. I guess you are confusing it with your other class that has 2 parameters
public ContactPerson(string in_Name, ContactNo in_No)
From your code it looks like you have to add this to your class ContactNo
public ContactNo(string type, string umber)
{
contactType = type;
contactNo = number;
}
Since you're passing a string and int I think you want to create a new ContactPerson, not ContactNo. However if you really want ContactNo, either add the constructor :
class ContactNo
{
public string ContactType { get; set; }
public string ContactNo { get; set; }
public ContactNo(string type, string no)
{
ContactType = type;
ContactNo = no;
}
}
Or (with the properties) initialize it like this :
ContactNo contact = { ContactType = "The type", ContactNo = "The No" };
public ContactNo(string type, string umber)
{
contactType = type;
contactNo = number;
}
Add this in your ContactNo Class.
The reason you get error is because there is no constructor with two parameters.
add the following to your ContactNo class:
public ContactNo(string inType, string inNo)
{
contactType = inType;
contactNo = inNo;
}
You don't have constructor to take 2 parameters. Add this constructor in your ContactNo class
public ContactNo(string contactType, string contactNo)
{
this.contactType = contactType;
this.contactNo = contactNo;
}
You need to declare the constructor for your ContactNo class. Classes only provides a default constructor with no arguments.
The constructor you need is the following:
public ContactNo(string contactType, string contactNo) {
this.contactType = contactType;
this.contactNo = contactNo;
}

Unity constructor parameters

class Entity:IEntityName
{
#region IEntityName Members
public string FirstName { get; set; }
public string LastName { get; set; }
#endregion
}
public class Person:IPerson
{
public IEntityName EntityName;
public Person()
{
}
public Person(IEntityName EntityName)
{
this.EntityName = EntityName;
}
public string ReverseName()
{
return string.Format("Your reverse name is {0} {1}",EntityName.LastName, EntityName.FirstName);
}
public override string ToString()
{
return string.Format("Name is {0} {1}", EntityName.FirstName, EntityName.LastName);
}
}
// Main Method
private static string DisplayReverseName(string fName,string lName)
{
IUnityContainer container = new UnityContainer();
container.RegisterType<IPerson, Person>().RegisterType<IEntityName,Entity>();
IEntityName entityName = container.Resolve<IEntityName>();
entityName.FirstName = fName;
entityName.LastName = lName;
var p = container.Resolve<IPerson>();
return p.ReverseName(); // firstName and lastName are still null
}
How can I inject the firstName and lastName into Person constructor ?
You can use a ParameterOverride like:
var p = container.Resolve<IPerson>(new ParameterOverride("EntityName", entityName));
This tells unity to supply the entityName instance to the constructor with the parameter named "EntityName".
You can find some additional info here: http://msdn.microsoft.com/en-us/library/ff660920(v=pandp.20).aspx

Categories