The constructor of the attribute decorating the main method is not called in release builds

Does anyone know why the attribute constructor decorating the main method is called in debug builds, but not in release builds?
How can I guarantee that the constructor is called in release builds? Of course, without calling it manually.

Any understanding of this topic would be greatly appreciated.

+3
source share
1 answer

I can reproduce this (both in debugging and in release), when executed through the IDE with the option "Debugging" => "Enable Visual Studio Hosting" enabled using below. On the command line, it will print “hello”, where, as through the IDE, it will print “world”. It seems that the IDE makes several different reflections in the attributes.

This expected behavior is not , and you should not rely on this behavior. If you want some specific code to be executed: explicitly call the desired code. To get predictable behavior, disable the "Debug" => "Enable Visual Studio Hosting" option.

using System;
public class MyTestAttribute : Attribute {
    public MyTestAttribute() {
        Program.text = "world";
    }
}
class Program {
    public static string text = "hello";
    [MyTest]
    static void Main() {
        Console.WriteLine(text);
        Console.ReadKey();
    }
}
+2
source

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


All Articles