Osama
Osama

Reputation: 335

C# string.Format throws exception

I am trying to format a string using string.Format but it throws an exception.

 var format = "public {0} {1} { get; {2}set; }";
        var arg0 = "long";
        var arg1 = "Ticks";

        var formatedString = string.Format(format, arg0, arg1, null);

The last line throws a System.FormatException with the following details:

    System.FormatException was unhandled
  HResult=-2146233033
  Message=Input string was not in a correct format.
  Source=mscorlib
  StackTrace:
       at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
       at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
       at System.String.Format(String format, Object arg0, Object arg1, Object arg2)
       at ConsoleApplication1.Program.Main(String[] args) in E:\lab\cheque\helloworldprism\ConsoleApplication1\ConsoleApplication1\Program.cs:line 11
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

Upvotes: 2

Views: 8408

Answers (2)

jacob
jacob

Reputation: 4956

You need to escape your curly-braces, using another curly brace will escape it.

var format = "public {0} {1} {{ get; {2}set; }}";

Upvotes: 5

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

It does not like the { and the } in the { get; {2}set; } you have to escape curly braces by using two of them

var format = "public {0} {1} {{ get; {2}set; }}";

Upvotes: 9

Related Questions