Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Providing a default value for an Optional Parameter in C# 4.0

Tags:

.net

c#-4.0

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
   }
}
like image 235
Dusty Avatar asked Feb 03 '26 14:02

Dusty


1 Answers

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.

like image 173
Jon Skeet Avatar answered Feb 06 '26 03:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!