I have the following code, that I use as sample for illustrating different scenarios:
public static void MethodWithOptionalGuid(Guid id = default(Guid)) { } public static void MethodWithOptionalInteger(int id = 2) { } public static void MethodWithOptionalString(string id = "33344aaa") { } public static void MethodWithoutOptionalParameter(int id, Guid longId) { } static void Main(string[] args) { var methods = typeof(Program).GetMethods(BindingFlags.Public | BindingFlags.Static).ToList(); foreach (var method in methods) { PrintMethodDetails(method); } Console.ReadLine(); } static void PrintMethodDetails(MethodInfo method) { Console.WriteLine(method.Name); foreach (var parameter in method.GetParameters().ToList()) { Console.WriteLine(parameter.Name + " of type " + parameter.ParameterType.ToString() + " with default value:" + parameter.DefaultValue); } Console.WriteLine(); } It prints the following:
MethodWithOptionalGuid id of type System.Guid with default value: MethodWithOptionalInteger id of type System.Int32 with default value:2 MethodWithOptionalString id of type System.String with default value:33344aaa MethodWithoutOptionalParameter id of type System.Int32 with default value: longId of type System.Guid with default value: The output seems fine for the last 3 methods.
My question is regarding the first one, MethodWithOptionalGuid: why the Guid's default value is not recognized?
I expected to receive something like "0000000-..." . I also tried initializing the optional parameter with new Guid() and same result. I tried as well other structs, like TimeSpan and the behavior is the same.
I expected that all value types would behave the same (as seen in integer example).
Extra: I found this thing while trying to use in Asp.Net MVC an action with an optional Guid parameter and failed (had to make the Guid nullable). Went through MVC code and found that it uses the DefaultValue at some point. So I made this code sample to better illustrate my issue.
MethodWithOptionalGuid. There a default value is specified and I too wonder whydefault(Guid)does not result in "0000.."idinMethodWithOptionalGuidit is "00000-"... so whyparameter.DefaultValueisnullinstead ofGuid.Emtpy?