Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd System.Format Exception [duplicate]

I am just trying to build a json string for my unit test and unexpectedly the following code returns system format exception. The error message indicates that it is trying to parse date which is quite odd to me. I am not asking to parse date.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(GetJson());
        Console.ReadKey();
    }

    static string GetJson(string dateStr = "", string lta = "5.25")
    {
        return String.Format("[{\"dateBooking\":\"{0}\",\"lta\":\"{1}\"}]", dateStr, lta);
    }
} 

It can be easily reproduced but I am adding exception details:

"An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Input string was not in a correct format."

like image 963
londondev Avatar asked Dec 24 '22 19:12

londondev


1 Answers

You need to escape the { with {{ and the } with }} because String.Format will search for an argument like {0:000} but instead finds {"dateBooking ... } which is no valid argument format. Thats why a FormatException raises.

return String.Format("[{{\"dateBooking\":\"{0}\",\"lta\":\"{1}\"}}]", dateStr, lta);
like image 71
a-ctor Avatar answered Dec 27 '22 08:12

a-ctor