Category Archives: C#

System.Reflection.TargetInvocationException

When you get a popup about this kind of exception in C#, select Break in the popup and then look in your Locals for the innerException property of this exception.  It will probably indicate something like “Exception thrown by type initializer of class“, which means you might be trying to do something like get the Length of an uninitialized string.

System.UnauthorizedAccessException

This can happen if you received the ASPX file via an IM file transfer, for example.  Look at the file’s Properties|Security|GroupOrUserNames, and if “Users” isn’t listed there, that means ASP.NET can’t access the file.

I fixed this by copying the file contents into the clipboard, reverting the file, and pasting the contents over the file.  (When you get the file from Perforce, the users list should be correct.)

ASP.NET supports Page_Error()

If one’s C# code throws an exception that isn’t explicitly caught by any try/catch, then  one can use ASP.NET’s Page_Error() method as a fallback…it’s invoked for all such thrown exceptions.  The default implementation just pops an error dialog.

Parsing strings into other types in C#

What’s the best way of parsing a string into some other type, and making sure nothing more is done if that conversion fails?  A typical way would be:

  try {
    int i = UInt.Parse(s);
  } catch (ex) {
    …blah blah
  }
  next step

but this requires that something happen in the ‘catch’ to prevent doing anything at ‘next step’, and often that is left to a TODO that never gets implemented.  Instead, try this:

  int i;
if (!UInt.TryParse(s, out i)) { return; }
next step

Using curly braces in a format string in C#

Because curly braces are used in C# to indicate where values should be pasted in, like this…

sb.AppendFormat(“Email: {0}”, sEmail);

…therefore, if you need to display curly braces in the final string, you’ll need to escape them, like this:

sb.AppendFormat(“var oContact = {email:'{0}’}“, sEmail);

Don’t use + to build strings

First, using + to create strings in JS is fine because there is no alternative.

But in C# and ASPX (and Java), string objects are “immutable”, which means you can’t alter their properties; when you use +, a whole new string is created to contain the two original pieces. So when you use a chain of +’s, you’re creating a lot of objects and then throwing them away.

Instead, use StringBuilder.Append or AppendFormat.  For example, change

  s = “[” + s + “]”;

to

//10 is an estimate of the final # of chars
  StringBuilder sb = new StringBuilder(10);
  sb.Append(“[“);
  sb.Append(s);
  sb.Append(“]”);
  s = sb.ToString();

or

  //10 is an estimate of the final # of chars
  StringBuilder sb = new StringBuilder(10);
  sb.AppendFormat(“[{0}]”, s);
  s = sb.ToString();

Note that this means you don’t want + inside your calls to Append, either.

Coding with empty string

When you need to put an empty string in C#  or ASPX code, use String.Empty rather than “”, since this saves creating an object for every appearance of “”.

When checking for empty string, create a utility method like !Util.NullOrEmptyString(s) instead of (s != null && s != “”).  It’s more readable, and one is less prone to forget that one usually has to check for both null and empty string.

“System.FormatException: Input string was not in a correct format.”

When using .Net’s StringBuilder, you might see this error. The likely cause is that you have a curly brace in the format string that you want to appear in the final string.  That will mislead .Net into thinking it’s a placeholder (the expected use of curly braces), and escaping with doesn’t seem to help.

Break up the format string so that the “literal” curly braces appear only in Append’s.