asaf92
asaf92

Reputation: 1855

How to avoid recompiling assemblies when changing constant values? (C#)

I'm trying to figure a way to have a static class with constant strings that doesn't force recompilation when values from this class changes.

I've read in this highly voted comment that:

... if you change a (const) value you must also recompile all assemblies dependent on your assembly defining the constants - therefore its often safer to go the readonly route.

So I did a short experiment to check if it's true.

I have 4 projects: Program, ProjectA, ProjectB & ProjectC. Each "ProjectX" has a single class "X" while program stores main.

In C I have a single public const string someString = "some const string", which is referenced by a public method in B, which in turn is referenced by a public method in A, and A's method is called by Program.Main.

Whether I make someString a const, a static readonly, a getter only expression bodied property or a getter only property with a property initializer, all the projects get rebuilt no matter what.

So is it true that I can have a static class that holds readonly string values that won't propagate recompilations to all depending projects once it's value is changed?

Upvotes: 1

Views: 331

Answers (1)

JonasH
JonasH

Reputation: 36371

There are two different issues here:

const means the value treated as a compile time literal. I.e. each time it is used the compiler will insert the actual literal value where it was used. This can be an issue if you dynamically load dlls, or use another version of a dll than it was compiled against. Read more about const vs static readonly.

The problem you are describing is the build dependency system. I.e. when doing an incremental build it will rebuild all modified projects and all projects that depend on a project that will be rebuilt. This behavior has nothing to do with const vs static readonly. Inserting a space in a code file is sufficient for the project to be considered modified.

If you only have four projects it is probably easiest just to live with it. If it is an actually a problem you could move the values to a configuration file so they can be changed without recompiling anything.

Upvotes: 1

Related Questions