Archive of: .NET

  1. Using Extension Methods in .NET posted September 3, 2010

    Extension methods are a handy way of adding your own custom methods to a class when you normally wouldn’t be able to. .NET treats extension methods exactly like instance methods. In fact, in your day-to-day .NET programming you may be calling extension methods and not even know it.

    Let’s say we have access to an API with a simple Person class. Also, for the purposes of this post, let’s say we don’t have access to extend or modify this class.

    public class Person {
    
      public Person(string first, string middle, string last) {
        FirstName = first;
        MiddleName = middle;
        LastName = last;
      }
    
      public string FirstName { get; set; }
      public string MiddleName { get; set; }
      public string LastName { get; set; }
    }
    

    In order to get the full name of a Person we’d have to do something like this:

    Person p = new Person("Robert", "N", "Greiner");
    string fullName = String.Format("{0} {1}", p.FirstName, p.LastName);
    

    This is perfectly fine, but what if you have to do this in several places? You’d either have to copy/paste this code wherever you needed it (bad idea, what if your boss came in later and said that she… Read the rest

  2. Using Stopwatches and Timers in .NET posted June 2, 2010

    Two problems that plague new programmers and seasoned professionals alike is the need to delay program execution and get an accurate time how long something takes to execute. Luckily, there are probably a few thousand ways to solve each problem. Unfortunately, most of them center around laziness (the bad kind) and unreliability. In this article, I’ll attempt to show you how to implement the different Timer and Stopwatch classes in .NET to help ensure your application will work as intended for years to come. Because, let’s face it, you probably aren’t going to be re-factoring any time soon.

    Timers

    First, we’ll start of with an introduction to Timers and how not to implement them. Timers allow you to control the execution of your application by being able to define when an action takes place.

    I remember in my very first high-school programming class, we were instructed to move a circle from one end of the screen to the other. The problem every student eventually encountered was, the circle had already moved to the edge of the screen by the time the graphics got loaded and we didn’t get to see any animation. This happened because the function that incremented… Read the rest

  3. Iterating Through a Dictionary in C# posted May 23, 2010

    A Dictionary allows you to store items in a collection using a key/value paring. By storing your data this way, you get all of the functionality of a standard .NET Collection with the added benefits of Hashing.

    I’m going to start off by showing you how to get data into a Dictionary. Then, I’ll move on to how to access specific data entries. And, finally, I’ll demonstrate two methods of iterating through the Dictionary. This should give you enough information to get started with Dictionaries if you’ve never seen them before, and hopefully, teach you something new if you are already familiar with them.

    Inserting Into a Dictionary

    First, let’s get some data into our Dictionary by adding some of the hard workers of Dunder Mifflin.

    Dictionary<int, Person> employees = new Dictionary<int, Person>();
    employees.Add(1000, new Person("Jim Halpert"));
    employees.Add(1001, new Person("Pam Halpert"));
    employees.Add(1002, new Person("Andy Bernard"));
    employees.Add(1003, new Person("Dwight Schrute"));
    employees.Add(1004, new Person("Michael Scott"));
    

    Retrieving Data From a Dictionary

    Now that we have our employees in memory, we can access them in near constant time (O(1)) by using their ID.

    Person p = employees[1003];  //Select Dwight
    

    Iterating Through a DictionaryRead the rest

  4. Write Better Code: Using Nullable With C# posted April 20, 2010

    I’m sure if you have ever written code for more than 45 seconds, you have more than likely come across a need to check whether or not a variable has been assigned a value.

    This is probably how about 99% of us do it:

    int age = 0;
    
    //some code that gets user input
    
    if (age == 0) {
      Console.WriteLine("Fail! Please enter a valid age.");
    } else {
      Console.WriteLine("You are now " + age + " years old");
    }
    

    The above code is bad for three reasons:

    1. The code is error prone. Why do things on your own, when the language provides a simple consistent way of doing things?
    2. The code isn’t standardized. What if you assign 0 as the official “un-assigned” check for all of your strings, but Johnny Programmer (in his super awesome wisdom) decides to initialize all of his un-assigned integers with -1, then what? Now you are forced to add unnecessary rules to your coding standards to ensure yours and Johnny’s code plays together nicely. This is lame.
    3. The code isn’t optimized. The fewest amount of bits to compare per if statement the better. why compare multiple Bytes when you can

    Read the rest

  5. Using #if and [Conditional()] to Keep Debug Code Under Control posted February 20, 2010

    The #if directive provides a perfect way to ensure your released executable doesn’t execute any code that was only intended for debug mode.

    #if (<symbol>) will return true whenever the symbol being checked has been defined by default, or manually using #define.

    #if DEBUG
    	//Perform debug only code
    #else
    	//Release-level code
    #endif
    

    Remember, this is only one application of #if, you can use it any time you need to check to see if a symbol has been defined.

    You can also use the [Conditional("<symbol>")] attribute on any method that has a return type of void. This will cause the compiler to remove all calls to the given method if the specified symbol is not defined.

    /* using System.Diagnostics; */
    [Conditional("DEBUG")]
    public void printDebug() {
    	Console.WriteLine("Debug Information");
    }
    

    Now printDebug() will not be executed unless the application is in debug mode.

    Either method will save you time and effort by allowing you to leave debug code in your application, as well as provide you a more standardized and safe way to include debug code.

.NET Algorithmic Art ASP ASP .NET ASP .NET MVC audio Bill Gates C# code review Computational Art CouchDB CSS Database DateTime debug DevDays eclipse ethics FileSystem Git Improvement iPhone Java JQuery Knopflerfish Layouts mail Microsoft Oracle OSGi Processing Python Ruby SMTP SOA Software Piracy Source Control SQL StackOverflow tools TortoiseGit training Web Standards Windows XHTML