1

so i have a class customer, the constructor customer has 5 parameters

 class customer
    {
        public customer(string fname, string lname, string address,DateTime dob, int phone, string email  )
        { }

parameters email and phone can be blanks. is there a way to accomplished it without creating another constructor that only takes the necessary fields?

Eddie Vu
  • 65
  • 1
  • 8
  • Though you could do optional parameters, is that truly the proper solution for your problem? I often find it isn't ideal. – Greg Apr 17 '18 at 23:48
  • Constructor chaining is another option. Or just let the calling client set those properties separately. – Rufus L Apr 18 '18 at 00:01
  • With this many parameters and multiple of them being optional it would be better to make properties (instead of fields there should be some anyways) and use the object initializer syntax, i.e. `new Customer { FName = "John", LName = "Doe", Address = "Evergreen Terrace 1", Phone = 5554321 }ˋ. Or do a combined approach by only making the fields that are truly required as constructor parameters (but than the constructor should check if they are truly filled out and not just null) and the optional ones as settable properties with the object initializer syntax. – ckuri Apr 18 '18 at 05:20

1 Answers1

1

You can simply use optional parameters:

class Customer 
{
    public Customer(string fname, string lname, string address, DateTime dob, int? phone=null, string email=null) { 
      // just check if phone has a value
      if (phone.HasValue) {
        // do something with phone.Value;    
      }
      // and check is email is not null
      if (email != null) { }
    }
}

And then just call the constructor as you would any method with optional parameters:

var c = new Customer("first name", "second name", "address", dob);

The omitted parameters will have their default values. Note that since phone was an int I had to change it to a nullable (int?).

Side note: In C# class names should use camel case. :-)

Loudenvier
  • 8,362
  • 6
  • 45
  • 66