The question is how the C # compiler emits TypeRef information

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?

+4
source share
1 answer

This can be seen as a bug in the compiler. If you carefully examine the assembly, nothing refers to the optional TypeRef attribute.

TypeRef will not be present in the resulting assembly unless you explicitly add TestMethod2 to it. It just shows that the attribute is added in the first pass and then removed. And it also shows that DefaultParameterValueAttribute is handled differently by the compiler.

Ultimately, this is really a small implementation detail, for example, the Mono C # compiler will not create a TypeRef for any attribute in the resulting assembly.

+3
source

Source: https://habr.com/ru/post/1347849/


All Articles