Tuesday, July 27, 2010

C# Tip - 7/26/2010

Make use of declarative programming when able to (use judiciously).  It will save time and allow for a clearer representation of your logic.

What is declarative programing?  It's when you define the behavior of the class using declarations instead of writing code.

Example:
[WebMethod]
public string HelloWorld()
{
  return "Hello World";
}

[WebMethod] <<< declarative programming

Another example is lambdas.  In the following example, retrieve all records that begin with "test":




            List lis = new List() { "test", "tests","unit","load" };
            List filteredList = lis.Where(l => l.StartsWith("test")).ToList();


Imperative example would be:

            List filteredList2 = new List();
            foreach (string list in lis)
                if (list.StartsWith("test"))
                    filteredList2.Add(list);


No comments:

Labels