Click here to Skip to main content
15,881,588 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Neeed year in cons string

C#
const string DATE_FORMAT = DateTime.Now.ToString('yyyy');


What I have tried:

C#
const string DATE_FORMAT = DateTime.Now.ToString('yyyy');
Posted
Updated 15-Dec-22 1:45am
v2
Comments
Stylus STYLUS 15-Dec-22 8:34am    
c#
PIEBALDconsult 15-Dec-22 7:40am    
You want QUOTEs ("); not APOSTROPHEs (').
Stylus STYLUS 15-Dec-22 8:34am    
Same error
Richard Deeming 15-Dec-22 8:56am    
What, the error that you mentioned in your question?

Oh, that's right; you didn't mention any error. You just showed some unexplained code that won't compile for a number of reasons, and told us you need a non-constant value in a constant string.

And yet based on the name of the constant, I suspect you may actually want to store the date format string, not the value for the current date.

Perhaps if you provided a clear explanation of precisely what you are trying to do and why, we might be able to help you.
Stylus STYLUS 15-Dec-22 9:09am    
const string DATE_FORMAT = DateTime.Now.ToString('yyyy');

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

error CS0133: The expression being assigned to 'Program.DATE_FORMAT' must be constant

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
Dave Kreskowiak 15-Dec-22 9:44am    
JFC, you are not listening AT ALL. YOU CANNOT USE const IN THIS CODE! CHANGE const TO readonly!
OriginalGriff 15-Dec-22 10:16am    
And there I was thinking I couldn't be much clearer ... :sigh:
Dave Kreskowiak 15-Dec-22 10:22am    
My laptop sometimes needs threats to get it to listen. I used to sit by a window on the second floor. ;)

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