Click here to Skip to main content
15,886,067 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I need to put year in database name connection string

Need to be

const string strCon2 = "Data Source=.\\SQLEXPRESS;Initial Catalog=BSS 2022;Integrated Security=True";

C#

I try to solve initial catalog

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());

C#

And result

const string strCon2 = "Data Source=.\\SQLEXPRESS;Initial Catalog="+konekcija+";Integrated Security=True";

C#

or

const string strCon2 = "Data Source=.\\SQLEXPRESS;Initial Catalog=BSS "+year+";Integrated Security=True";

C#

But I have error

A field initializer cannot reference the non-static field

What I have tried:

C#
const string strCon2 = "Data Source=.\\SQLEXPRESS;Initial Catalog=BSS "+year+";Integrated Security=True";
Posted
Updated 15-Dec-22 1:47am
v3

1 solution

You can't assign anything to a const field unless that initial value can be determined at compile time.

Use a readonly field instead, and set the value in the class constructor.
 
Share this answer
 
Comments
Stylus STYLUS 15-Dec-22 7:51am    
Example?
OriginalGriff 15-Dec-22 8:18am    
Example of what? You know how to use readonly and what a constructor is don't you?
Richard Deeming 15-Dec-22 9:03am    
Based on the DateTime.Parse(DateTime.Now.ToString()) in the question, I'm not so sure. :)
Stylus STYLUS 15-Dec-22 9:07am    
This is my conecction string

const string strCon2 = "Data Source=.\\SQLEXPRESS;Initial Catalog=BSS "+year+";Integrated Security=True";

Defined year
private readonly string year = DateTime.Now.Year.ToString();

This part of con string "+year+"; is problem

Error CS0236 A field initializer cannot reference the non-static field, method, or property 'Program.year'

Richard Deeming 15-Dec-22 9:09am    
Yes, as we keep telling you: a constant cannot refer to a non-constant value.

You need to make the field static and readonly. As I showed you below.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900