Strings in C# are
immutable - they cannot be changed once cretaed, and and attempt to change it creates a new string, just like it works with integers:
int x = 666;
int y = x;
x = x + 1;
console.WriteLine($"{x}:{y}:{666}");
Will always print "667:666:666" because anything else would make life very difficult indeed!
Similarly with strings:
string x = "Hello";
string y = x;
x = x + " world!";
Console.WriteLine($"{x}:{y}:{"Hello"});
Will always print "Hello World!:Hello:Hello" because the attempt to modify x created a new string, not modified the original.
In addition, in C# when you call a method, all the parameters you pass are passed by
value
, not by
reference
- which just means that the method gets a copy of the content of a parameter rather than the variable itself, and any changes made inside the method do not affect the "outside world".
Again, that's really necessary:
void Foo(int x)
{
x = x + 1;
Console.WriteLine(x);
}
Call that and see what happens:
inx x = 666;
Foo(x);
Console.WriteLine(x);
You get two lines:
667
666
Because the change inside the method affected the copy, not the original variable. Again, that makes sense - if it didn't work that way what would happen if you called it with a constant value:
Foo(666);
Console.WriteLine(666);
If the Foo method changed the external value so you got thsi printed:
667
667
Then every reference in your code to the constant 666 would now use 667 instead, and life would become very complicated indeed!
So your method returning
void
can't update the "outside world" with the new value and you do ned to return a string in order to pass it back to the caller.
static string Foo(string s)
{
return s + " World!";
}
string x = "Hello";
x = Foo(x);
Console.WriteLine(x);
Will print "Hello World!"
The "unhandled exception" is nothing to do with that, it's probably that what your user typed is not what you expected. Use the debugger: put a breakpoint on the line
DateTime d = DateTime.Parse(s);
And step through looking closely at what happens.
And in future, pats yoru code directly into your question using the "code block" paste option instead of posting it elsewhere and expecting other to go there and look. It's a waste of your time and ours! (and many people won't go near links from newbies because you just don't know what will be on the other end ... I ran up a VM just to open them!