If I have a Pet class with the get set methods for int, double and bool
is this correct?
public class Pet
{
private string name;
private bool age;
public Pet(string name, bool age)
{
this.name = name;
this.age = age;
}
public string Name
{
get { return name; }
set { name = value; }
}
public bool Age
{
get { return age; }
set { age = value; }
}
}
Main Method
Pet myPet = new Pet ("james", true);
would it be fine to put true in the object for bool?
No.
For this you'll have to create a custom constructor like:
public class Pet
{
public string Name { get; set; }
public float Weight { get; set; }
public bool Alive { get; set; }
//defining a custom constructor
public Pet(string name, float weight, bool alive)
{
this.Name = name; //assign input parameter value to the Property
this.Weight = weight;
this.Alive = alive;
}
}
If your class has int, double and bool properties then this object constructor
Pet myPet = new Pet("fish", 20.0, true);
Would not compile. The "fish" parameter is a string and the compiler will fail (assuming you're setting the property values in the object constructor)
You need an constructor for it:
public class Pet
{
public Pet(string type, double price, bool something)
{
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.