If we look at the implementation of IsOptional , we will see:
public bool IsOptional { [__DynamicallyInvokable] get { return (this.Attributes & ParameterAttributes.Optional) != ParameterAttributes.None; } }
It depends on the metadata flag, but as msdn says:
This method depends on the optional metadata flag. This flag can be inserted by compilers, but compilers are not required to do this.
This means that it depends on the compiler, and if we use another compiler, we can get the parameter whose default value will not have the IsOptional flag. Now let's see how the HasDefaultValue property is implemented:
public override bool HasDefaultValue { get { if (this.m_noMetadata || this.m_noDefaultValue) return false; else return this.GetDefaultValueInternal(false) != DBNull.Value; } }
It always checks if the parameter has a default value and is not dependent on the compiler. This may not be the 100% correct answer, just my thoughts.
UPDATE 0
Here's an example where the parameter has no default value, and IsOptional is true:
public static void Method([Optional]string parameter) { } ParameterInfo parameterInfo = typeof(Program).GetMethod("Method").GetParameters()[0];
Vyacheslav volkov
source share