Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
1.50/5 (6 votes)
See more:
string carName = "";
DateTime dateFrom = "";

Is there any error?
Posted
Comments
BillWoodruff 2-Feb-14 8:11am    
What happens when you execute those two lines of code ?

Yes. Next!


Oh, you want more details? OK...
if you try to compile that, you will get an error:
Cannot implicitly convert type 'string' to 'System.DateTime'

Because you can't just assign a string to a DateTime any more than you can push a square peg in a round hole.
DateTime is not a string data type: it's a value which represents the number of milliseconds since and arbitrary point of time. Even if you wanted to assign a "blank" value to it, you can't, because just like integer it doesn't have a concept of "blank number" - it has a zero, just like integers do (DateTime.MinValue) but it doesn't have a "blank" value, so even if your tried the "proper" way to assign a string value to a DateTime by using DateTime.Parse or DateTime.ParseExact it would throw an exception if you tried to parse a blank string!

Think about what you are trying to achieve and there may be a better way to try and get there - but that isn't going to work!
 
Share this answer
 
Comments
Rahul VB 2-Feb-14 10:01am    
no point explaining OG. I always get a feeling of Deja vu.
+5
I want you to observe the below stuff very keenly:



Quote:
string carName = "";
DateTime dateFrom = "";




Whats special in the below code??? Why does it compile???

Quote:
string carName = "";
DateTime dateFrom = DateTime.Parse("");



What if i do?
Quote:
DateTime dateFrom = Convert.ToDateTime("");




Last question:

What if you ask me 50$ and i give you 50Rs what is the difference?


Thanks
 
Share this answer
 
v3
Start from reading MSDN documentation:
DateTime[^]
String[^]

Do not initiate string variable this way:
C#
string carName = "";

use:
C#
string carName = String.Empty();



To propery set datetime variable, use this:
C#
DateTime date1 = new DateTime(2008, 5, 1, 8, 30, 52);
//or
DateTime date3 = DateTime.Today;
 
Share this answer
 
Comments
Nelek 21-Oct-14 19:32pm    
Wow, that can be named a big cache problem ;P
Maciej Los 22-Oct-14 2:33am    
;)

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