Does not contain a constructor that takes 2 arguments? - c#

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;
}

Related

How to get an output of an object stored in an array in C#

I am stuck at a really stupid mistake.
I want to create an object of the Class Car and store the objects in an array.
So far so good.
But I cant figure out how, or better to say why I cant get any output which makes sence with Console.WriteLine();
I am pretty sure the solution is simple as always, but I cant figure it out on my own.
This is my code
static void Main(string[] args)
{
Car audi = new Car("Audi", "A4", 4); //string Lable, string name, int tires
Car vw = new Car("VW", "Golf", 4);
Car[] carcollection = new Car[] {audi,vw};
Console.WriteLine(carcollection[0]);
}
So is there a way that i can write all the values of an object with Console.WriteLine() without typing in audi.Name, audi.Lable etc?
If using record is allowed. Try this: (.NET 5+)
public record Car(string Name, string model, int doors);
Then in your class:
public class MyClass {
public void ShowCarInfo() {
Car audi = new Car("Audi", "A4", 4);
Car vw = new Car("VW", "Golf", 4);
Car[] carcollection = new Car[] {audi,vw};
Console.WriteLine(carcollection[0]);
}
}
Output: Car { Name = Audi, model = A4, doors = 4 }
So you would define the class Car as follows: public class Gar
{
public string name;
public string label;
public string GetInfoOfCar()
{
return this.name + " " + this.label;
}
}
Then the "GetInfoOfCar" method will return the desired information.
To extract object information, you can do the following:
Console.WriteLine(carcollection[0].GetInfoOfCar());
As mentioned in comments, you can solve this by overriding Car.ToString():
public class Car
{
public string Name;
public string Label;
public int TireCount;
public Car(string label, string name, int tires)
{
Name = name; Label = label; TireCount = tires;
}
public override string ToString()
{
return $"{Label} {Name}, ({TireCount} tire{ (TireCount == 1 ? string.Empty : "s") })";
}
}
Now, whenever you call Console.WriteLine(carcollection[0]), Console.WriteLine will automatically call ToString() on the car and print Audi A4, (4 tires) for example.
Console.WriteLine requires an string input to correctly print result, so it converts your Car object to string by calling default ToString method. The default behaviour for this method is to provide full type name of your class as string object.
But you can override it in your class like this, or use Record type, example of which was provided in other answers.
class Car
{
public string Label { get; set; }
public string Name { get; set; }
public long Tires { get; set; }
public Car(string label, string name, long tires)
{
Label = label;
Name = name;
Tires = tires;
}
public override string ToString()
{
return $"Brand: {Label}, Label: {Name}, Tires: {Tires}";
}
}
class Program
{
static async Task Main(string[] args)
{
Car audi = new Car("Audi", "A4", 4); //string Lable, string name, int tires
Car vw = new Car("VW", "Golf", 4);
Car[] carcollection = new Car[] { audi, vw };
Console.WriteLine(carcollection[0]);
}
}

Dynamically creating and calling a class using Reflection in a console application

I have some problems about this section in C# language.
So I'm trying to do something like revealing reflection of this class and it's methods.
class Car
{
public string Name { get; set; }
public int Shifts{ get; set; }
public Car(string name, int shifts)
{
Name = name;
Shifts = shifts;
}
public string GetCarInfo()
{
return "Car " + Name + " has number of shifts: " + Shifts;
}
}
So I have this class Car, and this method GetCarInfo(), now, I'm trying to:
Dynamically create instance of this class Car, and dynamically calling a method GetCarInfo(), I would like to show result in console, but I can't when I run it it shows build errors. The application break every time.
Edit
Errors
Here's a example
namespace ConsoltedeTEstes
{
class Program
{
static void Main(string[] args)
{
//Get the type of the car, be careful with the full name of class
Type t = Type.GetType("ConsoltedeTEstes.Car");
//Create a new object passing the parameters
var dynamicCar = Activator.CreateInstance(t, "User", 2);
//Get the method you want
var method = ((object)dynamicCar).GetType().GetMethod("GetCarInfo");
//Get the value of the method
var returnOfMethod = method.Invoke(dynamicCar, new string[0]);
Console.ReadKey();
}
}
public class Car
{
public string Name { get; set; }
public int Shifts { get; set; }
public Car(string name, int shifts)
{
Name = name;
Shifts = shifts;
}
public string GetCarInfo()
{
return "Car " + Name + " has number of shifts: " + Shifts;
}
}
}

C# Base class constructor arguments

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;
}
}

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

Is it possible to create a class property that is a combination of other properties?

I want to combine a few string properties into a single string to make sorting and display easier. I was wondering if there was a way to do this without having to iterate through the collection or list of the class. Something like FullName in the below Person class.
public class Person
{
public string Last {get;set;}
public string First {get;set;}
public string FullName = Last + ", " + First {get;}
}
Update your class like so:
public class Person
{
public string Last { get; set; }
public string First { get; set; }
public string FullName
{
get
{
return string.Format("{0}, {1}", First, Last);
}
}
}
Additional to your question, I would also recommend implementing an override of the ToString() method (your question mentions making display easier) as most UI technologies will use this as a default way of displaying an object.
public override string ToString()
{
return FullName;
}
public string FullName {
get{
return Last + ", " + First;
}
}
Sure:
public string FullName
{
get
{
return FirstName + ", " + LastName;
}
}
Why not?
public string FullName
{
get { return Last + ", " + First; }
}
try this:
public string FullName
{
get
{
return Last + " " + First;
}
}
public string Fullname
{
get
{
return string.Format("{0}, {1}", Last, First);
}
set
{
string[] temp = value.Split(',');
Last = temp[0].Trim();
First = temp[1].Trim();
}
}
Yes. You can use a property in your class to do the same. Even Microsoft advises to make a void method in a class which just do simple operations with the fields of a class as a property instead of a method.
Use string interpolation, as it is easy and simple ;)
public class ApplicationUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get
{
return $"{FirstName} {LastName}";
}
}
}

Categories