Difference between readonly constant and static for obfuscating strings?

We run our .NET binaries using obfuscator (with at least the obfuscation function turned on), and later during the build process, do some basic checks to verify this. I was surprised to notice that by changing the lines from static readonly string to const string , the changed lines were now visible in plain text when viewing disassembled code (via ildasm output).

As for string obfuscation, what is the difference between const string and static readonly string ?

EDIT: For example, here is a small program:

 class Program { private const string MyConstString = "MyConstString"; private static readonly string MyStaticReadonlyString = "MyStaticReadonlyString"; static void Main(string[] args) { string myLocalString = "myLocalString"; Console.WriteLine(MyConstString); Console.WriteLine(MyStaticReadonlyString); Console.WriteLine(myLocalString); Console.WriteLine("Hit <ENTER> to exit"); Console.ReadLine(); } } 

Looking at the .il code, the only value in text format for const string . This is true for two different obfuscation tools:

 .field private static literal string a = "MyConstString" // using Dotfuscator .field private static literal string '[SOH]' = "MyConstString" // using RedGate SmartAssembly 
+4
source share
2 answers

For const fields, their value simply needs to be included directly in the assembly, there is no way around this. This is because the compiler must be able to get the value of such a field without executing any of your custom code.

With static readonly fields, an obfuscator can use a static constructor to execute whatever code he wants, which means they can be confusing.

+3
source

If it is static, then the string value exists in the program data segment, where it has an address and to which it refers (in code) at its address.

If it is const, then it contains a string literal in the code segment.

0
source

All Articles