简体   繁体   中英

Constructor allows to overwrite some variables of the class C#

I have this class:

class Item
{
    string reference;
    string name;
    double price;
    double tva;
}

I have a question: I'm trying to solve: write a constructor that allows to overwrite the reference and name during the instantiation.

Is this the right answer?

public Item(double priceHT, double RateTVA)
{
    Console.Write("Enter reference: ");
    reference = Console.ReadLine();
    Console.Write("Enter Name: ");
    name = Console.ReadLine();

    this.priceHT = priceHT;
    this.RateTVA = RateTVA;
}

Try the following:

public class Item {

   private string reference = string.Empty;
   private string name = string.Empty;
   private double price = 0.0;
   private double tva = 0.0;

   //initialize all properties
   public Item(string reference, string name, double price, double tva)
    {
        this.reference = reference;
        this.name = name;
        this.price = price;
        this.tva = tva
    }

    //use this one to only set reference and name
    public Item(string reference, string name)
    {
        this.reference = reference;
        this.name = name;
    }

}

Using this pattern all of your members will be initialized properly and you overwrite reference and name . Don't know the whole purpose, though.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM