Skip to content

Instantly share code, notes, and snippets.

@steven-r
Created March 5, 2015 08:39
Show Gist options
  • Save steven-r/eba9fda6d6e4b2c9e0ac to your computer and use it in GitHub Desktop.
Save steven-r/eba9fda6d6e4b2c9e0ac to your computer and use it in GitHub Desktop.
ArgumentNull exception for args with String.Format()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using RazorEngine;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int? val = null;
Console.WriteLine("Value is: " + String.Format("{0:N4}", val));
string value = string.Empty;
try
{
// now with razor
string template = "Hello @string.Format(\"{0:N4}\", Model.Value)! Welcome to Razor!";
string result = Razor.Parse(template, new { Value = val });
Console.WriteLine("razor output is: " + result);
}
catch (Exception e)
{
Console.WriteLine("Razor exception " + e.Message);
}
try
{
// now with razor and workaround
string template = "Hello @(string.Format(\"{0:N4}{1}\", Model.Value, string.Empty))! Welcome to Razor!";
string result = Razor.Parse(template, new { Value = val });
Console.WriteLine("razor with workaround output is: " + result);
}
catch (Exception e)
{
Console.WriteLine("Razor exception " + e.Message);
}
try
{
Type t = typeof(string);
MethodInfo info = t.GetMethod("Format", new[] { t, typeof(Object[]) });
string output = (string)info.Invoke(value, new object[] { "{0:N4}", val });
Console.WriteLine("Value is: " + output);
}
catch (TargetInvocationException e)
{
Console.WriteLine("String.Format(format, Object[] = null) exception " + e.InnerException.Message);
}
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment