I need to put year in database name connection string
Need to be
C#
const string strCon2 = "Data Source=.\\SQLEXPRESS;Initial Catalog=BSS 2022;Integrated Security=True";I try to solve initial catalog
C#
string year = DateTime.Parse(DateTime.Now.ToString()).Year.ToString();
const string naziv = "BSS ";
string konekcija = string.Concat(naziv, DateTime.Parse(DateTime.Now.ToString()).Year.ToString());And result
C#
const string strCon2 = "Data Source=.\\SQLEXPRESS;Initial Catalog="+konekcija+";Integrated Security=True";or
C#
const string strCon2 = "Data Source=.\\SQLEXPRESS;Initial Catalog=BSS "+year+";Integrated Security=True";But I have error
A field initializer cannot reference the non-static field

Pankajkumar PatelRank #181 · 13.4K reputationPosted Dec 15, 2022, 7:49 AM EST
Hi Goran Bibic,
Hence, instead of const you can use readonly in following way:
public class ConnectionString { const string strCon1 = "Data Source=.\\SQLEXPRESS;Initial Catalog=BSS 2022;Integrated Security=True"; readonly string strCon2 = "Data Source=.\\SQLEXPRESS;Initial Catalog=BSS 2020;Integrated Security=True"; public ConnectionString() { //strCon1 = strCon1.Replace("2022", "2023");//compile error string year = DateTime.Now.Year.ToString(); strCon2 = strCon2.Replace("2020", year); } public string getConnectionString { get { return strCon2; } } }Use it in another class:
ConnectionString objConnectionString = new ConnectionString(); Console.WriteLine(objConnectionString.getConnectionString);For more details:
Hope this will help you!
Vishal YelveRank #178 · 13.6K reputationPosted Dec 15, 2022, 10:05 AM EST
Declare static readonly year;
private readonly static string _year = DateTime.Now.Year.ToString();and use _year in your connection string.
John IwaszRank #811 · 2.8K reputationPosted Dec 29, 2022, 1:21 PM EST
private const string strCon1 = "Data Source=.\\SQLEXPRESS;Initial Catalog=BSS {0};Integrated Security=True"; . . . string strCon = string.Format(strCon1, DateTime.Now.Year);Using a placeholder ({0}) with string format gives you precise control.
Or you could use:
private static readonly string strCon1 = $"Data Source=.\\SQLEXPRESS;Initial Catalog=BSS {DateTime.Now.Year};Integrated Security=True";