1

I am trying to convert a DateTime and an int property into a string in a foreach loop. I need to put the information that is stored in the objects properties into the variables and then use that info to write to a text file using StreamWriter. I'm not quite sure what I am doing wrong. Parse is red underlined with this error message -

Error 2 'string' does not contain a definition for 'Parse'

Here is my code -

 public bool Save()
        {
            string appointStart;
            string appointLength;
            string appointDescription;

            foreach (Appointment appointment in appointments)
            {
                appointStart = string.Parse(appointment.Start);
                appointLength = string.Parse(appointment.Length);
                appointDescription = appointment.DisplayableDescription;

            }
            return true;
        }

Thank you

4
  • String does not have a Parse method. Are you looking for formatting? Commented Jun 8, 2015 at 10:56
  • Error message is clear. There is method as Parse in String class. Can you please show an example input and outputs? Commented Jun 8, 2015 at 10:56
  • 1
    Parsing is converting from a string into a different type. Formatting is converting from the other type into a string. So you're not parsing into a string - you're formatting a DateTime. Commented Jun 8, 2015 at 10:56
  • Just use .ToString(). Commented Jun 8, 2015 at 10:56

2 Answers 2

5

Use the ToString() methods of DateTime and Int32 class to get a string representation of the specified types. Some ToString() methods provide overloads to define the formatting of the string value.

foreach (Appointment appointment in appointments)
{
  appointStart = appointment.Start.ToString();
  appointLength = appointment.Length.ToString();
  appointDescription = appointment.DisplayableDescription;
}
Sign up to request clarification or add additional context in comments.

1 Comment

The OP should also take care to use the proper format strings, to avoid writing unexpected values, eg time values when only dates were expected, US date formats instead of ISO etc
0

Why do you need to Parse the DateTime and int into String?? Because if you just want to have the variables in string format, you can simply use .ToString() or Convert.Tostring()

2 Comments

Thank you. I am new to programming and I am learning so I was not aware
Its okk... Free feel to ask and do me a favour, if my answer was helpful then please mark it as accepted answer and vote it up. Thank You!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.