C# - Palindrome

13. July 2011 18:00


Another common interview question is to write a function to detect if a string is a palindrome. For thoose who are not aware a palindrome is the same word spelt backwards as forwards eg "RACECAR".


Places tend to ask this because it can be solved in multiple ways. The two main methods are either using a for loop or using recursion. I don't think the recusion method is an advantage in c# because of the lack of pointers. So that method is going to be skipped here. The reason why they ask this is because it has a nice catch on how the issue of how to deal with an odd number of letters. This is actually very simple since the odd letter is in the middle it will be compared to its self. So there is never any need to compare the middle letter. An example is "RAC" "E" "CAR".


Here is a solution that will work for both even and odd cases ..


public static bool IsPalindrome(string str)
    for (int i = 0; i < str.Length / 2; i++)
        if (str[i] != str[str.Length - (i + 1)])
            return false;
    return true;


Something that is intresting is that as well as a simple technical test the interviewer can challange on the functionality of the operation of the odd case. Sometimes they do this to see if the person is going to defend them self or just role over and show a lack of confidence in their solution.

E-mail Kick it! DZone it! del.icio.us Permalink

C# - Interviews The string Reverse

11. July 2011 18:00


Another interview favorite is the string reverse. The question is simple. Write a function to reverse a string.


Very simple solution to this.


static string Reverse2(string str)
    char[] tmp = new char[str.Length];
    for (int i = 0; i < str.Length; i++)
        tmp[i] = str[str.Length - i - 1];
    return new string(tmp);


Or you might want to answer it something like this.


static string Reverse(string str)
    char[] tmp = str.ToCharArray();
    return new string(tmp);



The second solution shows more understanding of the c# language it also produces cleaner code. Which is easy to read.


Interviews tend to ask this because it shows dealing with array's and strings. Arrays in c# start at zero but the length's are a total number of items. So lots of people get the answers wrong normally because they forget to convert the length's to the array offsets.

E-mail Kick it! DZone it! del.icio.us Permalink

C# - Interviews FizzBuzz

10. July 2011 20:13


I am going to be posting some interview questions. So lets start with something really simple. There is a large number of people who consitantly fail the fizz buzz test.


The question is simple. Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".


The solution is also very simple.


static void Main(string[] args)
    for (int i = 1; i <= 100; i++)
        if (i % 5 == 0 && i % 3 == 0)
        else if (i % 5 == 0)
        else if (i % 3 == 0)
        } else {



The above is a simple test to verify that the person taking the test has the ability to convert logic written in english to logic written in code. For some reson there are a large number of people who still fails this. Here is the list of most common failures and excuses I have seen and what I though about them at the time.



  • They start the loop from 0 instead of 1
  • They get the order of the the if / else if wrong. They check for the i mod 3 before checking for i mod 3 and i mod 5.
  • They get the order of the if wrong. They print out BuzzFizz instead of FizzBuzz.



The best excuse that I have heard about it is typically oh. Its the stress of a job interview. I would agree that interviews can be stressful. However so can work. The candidate has just told me that they crack under pressure and will be unable to perform inhigh pressure situation or when trying to fix bugs in a stress enviroment eg a tight deadline.

E-mail Kick it! DZone it! del.icio.us Permalink

C# - Dynamic SQL

30. June 2011 18:00

Over the last number of years I have seen a lot of code which has been used to generate lots of dynamic sql. There has always been one thing in common with the way that I have seen this be done. Typically the approach is to have a string and just directly append everything to the end of the string during a button press or some such from the interface. I have seen cases where the c# code to produce a dynamic query have been over 200 lines. It would typically resemble something along the lines of this.


void MyEvent_Click() {
	string sql = string.Empty;
	sql += "ALTER INDEX [" + IndexName + "] "
	sql += "ON [" + TableName + "] " + Action;


The above is a simple case of making some dynamic sql. It is quite common to have something like above buy using dynamic joins and multiple optional conditions. Other bad things also start to happen where the code is then copied from place to place. It becomes difficult to maintain and almost impossible to test all the posisble combinations of options in the dynamic query. Not the mention that the code becomes more complex when you start to add join's and where clauses at the same time it causes problem because they both need to be added to different locations to the string.


Here is an alternative method. Simply come up with a class which sole purpose is to generate the sql for the query. Then the usage in the user interface code becomes significatly cleaner because it is only moving options / choices into the structure that will eventually build the query. This does also work with any other sql statement. The basic principle is to store all the required information in non sql form until the sql is actually required to be executed. This has a number of benifit's. It will also allow you to modified any part of the sql statement at any time in your code.


Here is a simple example that I pulled out of the index rebuild tool I made.


public class IndexWorkItem
    public string TableName = null;
    public string IndexName = null;
    public IndexWorkItemAction Action = IndexWorkItemAction.None;

    public SqlCommand ToSqlCommand()
        if (Action == IndexWorkItemAction.None)

        SqlCommand sql = new SqlCommand(string.Format(@"
            ALTER INDEX [{1}] ON [{0}] {2}
        ", TableName, IndexName, ActionToSQL(Action)));

        return sql;

    private string ActionToSQL(IndexWorkItemAction Action)
        switch (Action)
            case IndexWorkItemAction.Rebuild:
                return "REBUILD";
            case IndexWorkItemAction.Reorganize:
                return "REORGANIZE";
                throw (new NotImplementedException());

public enum IndexWorkItemAction
    None = 0,
    Reorganize = 1,
    Rebuild = 2


The main benifits of doing this are quiet clear.


  1. Easy debugging. You can seperate the dynamic query away from the interface code.
  2. Easy to test. Unit tests can be created to test almost every possible combination of the query.
  3. Testing has a major advantage because you can ensure backwards compatibility from existing code if the class changes.
  4. Cleaner / easy to maintain code.
  5. Possible to support multiple database engine's by adding additional functions. ToSqlCommand / ToMySql / ToOracle / etc..
  6. Easy to expand to support more options.
E-mail Kick it! DZone it! del.icio.us Permalink

C# - HowTo Parse a URL

27. June 2011 08:00


Something that seems quite easy to do is to parse a url. This is actually very easy in c#. However if you search on google you will see all sorts of solutions to it. Using regular expressions and various other ways to do it. Most of which I have always found really ugly. If your going for this method you really have to think about the fact that it has been a problem now for over 20 years and there must be a more common solution.


Some of these extreme methods may include something like this.


Protected Function ExtractDomainFromURL(ByVal sURL As String) As String
	Dim rg As New Regex("://(?<host>([a-z\d][-a-z\d]*[a-z\d]\.)*[a-z][-a-z\d]+[a-z])")
	If rg.IsMatch(sURL) Then
        	Return rg.Match(sURL).Result("${host}")
		Return String.Empty
	End If
End Function


Something like that is may work but. Can you read it again in six months time?

What about the path? What about correctly decoding the path? What about the paramaters?


You can do this in c# by adding a reference to System.Web and using the following code.


class Program
    static void Main(string[] args)
        Uri tmp = new Uri("http://www.google.co.uk/search?hl=en&q=parsing+a+url+in+c%23&aq=f&aqi=g1g-j9&aql=&oq=");

        Console.WriteLine("Protocol: {0}", tmp.Scheme);
        Console.WriteLine("Host: {0}", tmp.Host);
        Console.WriteLine("Path: {0}", HttpUtility.UrlDecode(tmp.AbsolutePath));
        Console.WriteLine("Query: {0}", tmp.Query);
        NameValueCollection Parms = HttpUtility.ParseQueryString(tmp.Query);
        Console.WriteLine("Parms: {0}", Parms.Count);
        foreach (string x in Parms.AllKeys)
            Console.WriteLine("\tParm: {0} = {1}", x, Parms[x]);



The program will produce the following output. With a correctly decoded url and access to the query string.


Protocol: http
Host: www.google.co.uk
Path: /search
Query: ?hl=en&q=parsing+a+url+in+c%23&aq=f&aqi=g1g-j9&aql=&oq=
Parms: 6
        Parm: hl = en
        Parm: q = parsing a url in c#
        Parm: aq = f
        Parm: aqi = g1g-j9
        Parm: aql =
        Parm: oq =


Enjoy Laughing

E-mail Kick it! DZone it! del.icio.us Permalink