Convert date to string

I have a string variable st and I assigned this string variable to output the next form data table using this statement

 string st; if(dt!=null) { if(dt.rows.count> 0) { st = dt.Rows[3]["timeslot_StartTime"].ToString(); } } 

now I want to convert this string variable to a date date property, and I did this using the statement below

 DateTime pt1 = DateTime.Parse(st); 

but it shows an error in st saying that use of unassigned local varaible "st" .

0
c # datetime time
source share
7 answers

You are probably using a variable in a different scope from the one where it was assigned, for example

 string st; if (condition) { st = dt.Rows[3]["timeslot_StartTime"].ToString(); } DateTime pt1 = DateTime.Parse(st); 

So, st not always initialized (this is only if the if condition is checked). Try instead

 string st; if (condition) { st = dt.Rows[3]["timeslot_StartTime"].ToString(); DateTime pt1 = DateTime.Parse(st); } 
0
source share

Initialize st to null or string.Empty

 string st = null; 

and to be on the safer side, check st for null before parsing.

+3
source share

Give st initial value, e.g.

 string st = String.Empty; 
+1
source share

try defining st this way

 string st = "" 
+1
source share

try to do it

 string st = null; 

check st if it is not null before parsing

+1
source share

You assign st inside your if logic. If you try to use st outside these blocks, you will encounter the error "unassignment".

Or

  • Give the variable a default value when initializing it
    • something that can be parsed, or remember to enable validation before trying to parse
  • or try to parse it on a DateTime at the point where you are retrieving a value from a data table

Of course, given that you are pulling the value from the DataTable, if the value is already stored in the table as a date, forget ToString() and parse everything.

 DateTime date = (DateTime)dt.Rows[x]["ColumnName"]; 
0
source share

You need to initialize the string. Currently, any initialization or assignment is done in the if block. The compiler detects this and believes that it is never initialized.

 string st = string.Empty; 

As an additional note, it is much safer to use similar TryParse () methods for chains to ensure that you will not have any unexpected exceptions caused by an incorrect formatting error. The method will return true if it was successfully converted, which makes it clean:

  if (dt!=null) { if(dt.rows.count> 0) { st = dt.Rows[3]["timeslot_StartTime"].ToString(); } } DateTime dt = DateTime.MinValue; if (DateTime.TryParse(st, out dt)) { //was successful and do something here } 
0
source share

All Articles