I found this interesting thing when I tested the new "advanced options" feature in C # 4.0.
I know that there are two ways to use "optional parameters" in C # 4.0:
static void TestMethod(int parameter = 5) { } static void TestMethod2([Optional, DefaultParameterValue(5)]int parameter) { }
Now, if I compile this code and then view the assembly using IL Dasm, then I will see that in the MetaInfo window of IL Dasm there is a type reference to an optional attribute as follows:
Token: 0x01000002 ResolutionScope: 0x23000001 TypeRefName: System.Runtime.InteropServices.OptionalAttribute MemberRef #1 (0a000001) ------------------------------------------------------- Member: (0a000001) .ctor: CallCnvntn: [DEFAULT] hasThis ReturnType: Void No arguments.
But there is no sign of DefaultParameterValueAttribute. Why is this?
In fact, I think that both attributes should not be here, because they are handled differently by the compiler, they have their own flag values. To explain what I mean, please take a look at this:
Method #2 (06000002) ------------------------------------------------------- MethodName: TestMethod (06000002) Flags : [Private] [Static] [HideBySig] [ReuseSlot] (00000091) RVA : 0x00002053 ImplFlags : [IL] [Managed] (00000000) CallCnvntn: [DEFAULT] ReturnType: Void 1 Arguments Argument #1: I4 1 Parameters (1) ParamToken : (08000002) Name : parameter flags: [Optional] [HasDefault] (00001010) Default: (I4) 5 Method #3 (06000003) ------------------------------------------------------- MethodName: TestMethod2 (06000003) Flags : [Private] [Static] [HideBySig] [ReuseSlot] (00000091) RVA : 0x00002056 ImplFlags : [IL] [Managed] (00000000) CallCnvntn: [DEFAULT] ReturnType: Void 1 Arguments Argument #1: I4 1 Parameters (1) ParamToken : (08000003) Name : parameter flags: [Optional] [HasDefault] (00001010) Default: (I4) 5
This is the metadata of these two methods. We can see that the default parameter value is already stored in the last line of each section of the code, so why is the optional attribute still referenced?
source share