Categories
ASP.NET C# VB.NET

String.Format to set a constant in .NET

Today I began working on the base framework for a new project. In the past we would just copy an existing project and remove what we don’t need, so I thought this would be a good time to make the framework more generic to speed up this part of the process for future projects. This also would prevent having to copy and replace for constants, variables, functions, class names, etc. based on the name of the project as we’ve done in the past. I say all of this to point out something I found that was new to me.

There were constants in the framework that needed to be changed, for example:

Private Const cUserName As String = "ProjectUserName"

Where “Project” in “ProjectUserName” would need to be changed based on the name of the project, this happen for several other constants. So I tried setting the constant like this:

Private Const cName As String = String.Format("{0}UserName", AppSetting.ProjectID)

And got “Constant expression is required.” which wasn’t clear to me. After some research I found that a constant has to be set by a compile time constant and the result of String.Format isn’t a compile time constant.

I finally just changed the constant to a shared readonly variable.

Private Shared ReadOnly cUserStoreName As String = String.Format("{0}UserName", AppSetting.ProjectID)