Q:

Test string for C#ness or VBness

What would be a halfway reliable way to determine whether a string represents VB.NET or C# code? It doesn't have work in all cases so an algorithm that's right more than 50% of the time is better than nothing.
I came up with the following, but it's pretty darn primitive.
public static ExpressionLanguage TryDetermineLanguage(string text)
{
  int csCount = 0;
  int vbCount = 1;

  csCount += text.Count(';');
  csCount += text.Count("//");
  csCount += text.Count("/*");
  csCount += text.Count("{");
  csCount += text.Count("}");

  vbCount += text.Count("If");
  vbCount += text.Count("Then");
  vbCount += text.Count("Else");
  vbCount += text.Count("End");
  vbCount += text.Count("Return");

  if (vbCount > csCount)
    return ExpressionLanguage.VisualBasic;
  if (csCount > vbCount)
    return ExpressionLanguage.CSharp;

  return ExpressionLanguage.Unknown;
}

I've got access to Roslyn in my project, but I'd like for this to work without going through a full parse and compile cycle.

A:

This depends entirely on how well you want it to work. A pretty simple minded way that would likely work well is to count the occurrence of the characters { and } compared to the occurrence of the word "End". Most likely if there are more { and } than End, then it's C#.
A more reliable way that takes a little more work would be to examine a lot of C# and VB code to build and store a trigram model of each language. Then, given a particular bit of code, build a histogram of the trigrams in that code and compare it against the stored models.
Both of those techniques can fall apart in the presence of large quoted strings and comments, unless your program has the smarts to identify and discard text in quoted strings and comments. But if you're not worried about those edge cases, I suspect the first technique above would do a pretty good job in most cases.

