How do I set a default if one of the parameters is a custom type?
public class Vehicle
{
public string Make {set; get;}
public int Year {set; get;}
}
public class VehicleFactory
{
//For vehicle, I need to set default values of Make="BMW", Year=2011
public string FindStuffAboutVehicle(string customer, Vehicle vehicle)
{
//Do stuff
}
}
You can't, really. However, if you don't need null to mean anything else, you can use:
public string FindStuffAboutVehicle(string customer, Vehicle vehicle = null)
{
vehicle = vehicle ?? new Vehicle { Make = "BMW", Year = 2011 };
// Proceed as before
}
In some cases this is nice, but it does mean you won't catch the situation where a caller accidentally passes null.
It would probably be cleaner to use an overload instead:
public string FindStuffAboutVehicle(string customer, Vehicle vehicle)
{
...
}
public string FindStuffAboutVehicle(string customer)
{
return FindStuffAboutVehicle(customer,
new Vehicle { Make = "BMW", Year = 2011 });
}
It's also worth reading Eric Lippert's posts about optional parameters and their corner cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With