Interfaces are an integral part of .NET, yet a lot of new .NET developers (especially those coming from weakly-typed languages, or languages where interfaces aren't supported) have difficulty in understanding why they're needed and how (and when) they're used. If you find yourself in that group you're in good company. It's not a difficult concept but it can be a bit foreign to developers new to them.

Let's get the textbook definition out of the way, then take a look at what it really means (and why you should even care). From Wikipedia:

"Interface generally refers to an abstraction that an entity provides of itself to the outside. This separates the methods of external communication from internal operation, and allows it to be internally modified without affecting the way outside entities interact with it, as well as provide multiple abstractions of itself. It may also provide a means of translation between entities which do not speak the same language, such as between a human and a computer."

Hmm - OK. While technically correct that doesn't really help, does it? Did your eyes glaze over like mine did while reading that? Maybe if we back up a bit and look at what a class is we might be able to make some sense of this.

The Basics

A class is a collection of methods, properties, and events. It is assumed that each of these methods, properties, and events "do something". At least in most cases (we're going to ignore the idea of an abstract class for right now). So far, so good. You can create a new instance of this class and do things with it, pass it around to other classes as a parameter, etc. In a weakly typed language (also known as a "dynamic language") you can pretty much pass any type of class around without having to worry about the type - as long as your code doesn't try to access a property or method that object doesn't have, you're good to go. The upside to this is that it's pretty flexible. The downside to this is that mistakes aren't caught at compile time - your app. just blows up at runtime (so you'd better test!). Strongly-typed languages take a different approach: you must define the types that can be passed as parameters to methods. That's OK as long as there is only one specific type your method acts on, or the type you're passing in inherits from the base type of the parameter - it's pretty straightforward. The upside is that mistakes (like trying to access a property or method that doesn't exist) is caught at compile time. The downside is that it's not as flexible as a dynamic language.

So what do I mean by "not as flexible"? On the surface it seems pretty reasonable that a strongly-typed method only accepts specific types - how else would the compiler (and you) know that it's safe to access a specific method or property? It doesn't. It only can accept that specific type of class, or any subclass of that same type.

Why is it OK to accept a subclass of the type? Well, the compiler can be sure that the subclass has the same exact properties & methods as its parent (it doesn't care if you add more of them or override the behavior).

But what if it doesn't? What if you had a class that wasn't of the correct type necssary to pass into a method and it didn't inherit from that type either? Let's take a look at an example of this. I wanted to keep it simple enough to understand, but have it be a REAL scenario (not some contrived example). Those goals are a bit difficult to balance so I error'd on the real scenario side of things. Hopefully it'll help you understand WHY some things are the way they are in the framework in addition to understanding interfaces.

A Real Example

For example, let's suppose we create a collection class that can have a collection of objects (that are all of the same type) and we want to have a method which can sort them. You want to write a generic Sort routine on your collection class that can sort any kind of collection of objects, as long as they're the same type. The first issue you'd run into is, "How do I generically create some code which can compare ANY type?" Remember - you have to be able to compare strings, numbers, date/times, maybe custom types someone may have created, etc. So it's not really possible to be able to compare ANY type. You could cover the basic types and then require the user to subclass your collection for any other custom types. It's a bit clunky, but it would work.

What if, instead, we decided that we'd have another class responsible for doing the sorting. We'd provide a default implementation and if you had your own custom types that needed to be sorted you could pass in your own implementation. That's a bit better. The developer would still need to subclass from our default implementation (since we've still got the strongly-typed issues here - again, dynamic languages don't have this "issue"). We could have the developer pass in their version of the class which does the comparison into the Sort() method. The passed in class would have a Compare() method and let's say it takes two parameters of the types of the same type of object and returns an integer value indicating whether one of the objects is less than, greater than, or equal to the other.

Let's take a look at what the code might look like for all of this:

public class Comparer
{
    public int Compare(object x, object y)
    {
        // Code to do comparisons here
    }
}

public class SampleArrayList
{
    public virtual void Sort()
    {
        this.Sort(new Comparer());
    }

    public virtual void Sort(Comparer comparer)
    {
        // Do sorting here. Call out to comparer object to do the actual comparison
    }
}

 

SampleArrayList list = new SampleArrayList();
// Add items to the list
list.Sort(); // default implementation
list.Sort(new SomeComparerSubclass()); // A custom sort


That looks OK. If I wanted to create my own comparison class all I'd do is subclass from Comparer and override Compare() with my own implementation. But let's take a step back and think about this for a bit. If you create a new class and want a method that can compare one instance of that class to another instance of it, where's the best place for the code? Doing comparison's is a pretty fundamental capability of a class - we do it all the time with string's, numbers, datetimes, etc. so clearly it belongs with the class, right? Your only other alternative would be to put it into another class that acts as a kind of "helper". That's effectively what we've forced on any developers that want to use the sorting capability of our collection for their own custom classes. They MUST create a helper class to do a comparison or they'd all have to inherit from our Comparer class (and use it as their base object). That might not be the end of the world but we're only talking about a single example - there are a lot of other places where this scenario comes up.

OK, having to create another class which only does a comparison for a specific type isn't all that great. Since it makes more sense to have a comparison handled by the object being compared, let's say we add a method called CompareTo() to any class when we want to be able to compare it against another instance. In our Comparer class we'll call that method and, hey, our comparer class is now a bit more generic right? We know that in .NET all objects inherit from "System.Object" so having our Comparer class's Compare() method accept "objects" means we can use it with ANY type. I don't actually have to create a new class for each and every item I'm going to compare! But wait - we're STILL going to have the problem with calling the CompareTo() method on our class in the collection; we're back to having to inherit from a common base class.

 

public class Comparer
{
    public int Compare(object x, object y)
    {
        // Code to do comparisons here
        return x.CompareTo(y.CompareTo());
    }
}

But now how can we call the CompareTo() method on those objects? How do we even know if those objects have a CompareTo() method? Since .NET is strongly typed you can't do this - it won't even compile. The class type "object" doesn't have a "CompareTo" method. The .NET compiler knows that and it won't let you do that.

This is begining to feel like a circular issue, isn't it?

Breaking the Cycle

OK, now what? Well, you could jump through a lot of hoops and use reflection to make the method call for you. But it's a lot of work. In a dynamic language (such as Visual FoxPro) code like that is perfectly valid - I can pass any object type into a method like that and access any properties or methods and VFP doesn't care. If the object doesn't have those properties or methods it will just blow up at runtime. I'm a good developer so I won't pass in something that would blow up. .NET sucks - it makes things so difficult.

You're basically stuck at this point - you can't do what you'd like to do in .NET. If .NET supported the idea of multiple inheritance (where class C could inherit from Class A and from Class B at the same time), we'd be able to still make this work. But it doesn't.

Interfaces to the Rescue

That's where interfaces come in (finally!). Let's take another stab at a more concrete definition of an interface: An Interface is a definition of the types of properties, events, and methods a class needs to implement. It's nothing more than a list of properties, events, and methods (and the various types associated with them) that a class has to have. While we can't inherit from multiple classes in .NET, we can inherit from multiple interfaces.

Getting back to our example, we could define an interface that consists of a public method called CompareTo that accepts one parameter of the "System.Object" type ("object" for short). This method needs to return an integer: Less than zero means this instance is less than the object passed in, zero means it's equal, and greater than one means it's greater than the passed in object.

Here's what it might look like:

public interface IComparable
{
    int CompareTo(object obj);
}

While we're at it, it seems like we might want to do something similar to our Comparer class:

public interface IComparer
{
   int Compare(object x, object y);
}


Now all we'd need to do is make sure that any class that we want to compare inherits from the IComparer interface and then "implements" the specified properties, methods, and events (PEM). That is, you need to make sure your class has all of the same PEM's as the interface. Then you use the interface as the parameter type instead. Since we can inherit multiple interfaces on a given type we have a way of giving our classes the cameleon-like ability of appearing as exactly the right type to methods, regardless of what class it really inherits from. We'd do the same thing for any class which can compare two different classes.

So we can rewrite the above code:

public class Comparer : IComparer
{
   public int Compare(object x, object y)
   {
       // Code here which compares x to y and returns integer
   }
}

public class MyCustomClass : IComparable
{
   public int CompareTo(object obj)
   {
   }
   public int CompareTo(MyCustomClass obj)
   {
   }
}


And we rewrite the Sort() method on our collection class SampleArrayList to accept objects of type "IComparer" instead of "Comparer": 

public void Sort(IComparer comparer)
{
   // Code here that iterates over the collection and class Compare()
   // with two of the items in our internal list.
}


Suddenly all of this starts working again - you get compiler-time checking to make sure things don't blow up, Intellisense works, etc. In fact the compiler verifies that you have, in fact, done all of this correctly - if your classes don't implement IComparer or IComparable it will let you know. You have the ability to create a custom class that compares objects in different ways (which makes it easy to come up with different ways of sorting, ex. ascending, descending) and have generic code which will work in most cases.

Conclusion

The scenario I described above plays out throughout the .NET framework. Fundamental things like garbage collection are handled via the IDisposable interface, iterating over a collection (think foreach) is handled by IEnumerable, comparing objects (like we described above) is handled by IComparer and IComparable. Interfaces are used extensively. Hopefully you've gotten a feel for why they're needed and how they're used inside of .NET.

Originally published in Universal Thread Magazine, April 2009


 
Categories: .NET | C#

I've been working on a server monitoring Windows service recently - it's meant to keep an eye on our servers for various types of failures and, if possible, automatically recover from them. One of the failures our website experiences once in a while has to do with our forums. I integrated a third party forum package into our site so our stores have a place to post messages and talk with one another. Occasionally (and I have yet to reproduce the failure steps) it will fail, complaining that it can't find some configuration file. The quick fix is to reset IIS; usually I'll just remote into the server and do an IISRESET from the command prompt. I wanted my service to keep an eye out for this type of failure and automatically recycle IIS. Long term I'd love to track down this failure and fix it the proper way but in the meantime I just want to be able to recover gracefully.

I found the ServiceController class after a bit of digging and wrapped it up into two static methods I could call to reset IIS. I just had to figure out the name of the service I needed to refer to. The easiest way I found of finding this was to just cycle through the services and display their names. You could write a quick console app. to do this, but I just used LINQPad, switched it to C# Statements, added a reference to the System.ServiceProcess.dll (hit F4), then added the namespace System.ServiceProcess and ran the code.

As an aside: I can't say enough nice things about LINQPad - it makes it so nice to be able to test out new classes and ideas. Its name would lead you to believe it's only good for testing LINQ queries, but you can test out almost any .NET code you want. I spent the whopping $19 to upgrade to the full version, which adds Intellisense (the free version doesn't include that). I've added LINQPad to my "must have" .NET toolkit.

image

You might be wondering what the Dump() method does, since it's not part of the ServiceController class. LINQPad has a nice extension method named Dump() that makes it trivial to dump out the response from almost anything. My sample doesn't show it, but it even handles nested classes nicely. OK, enough fawning...

I ran this code which made it really easy to find the service names I was interested in. Once I had them I wrapped up a few of the services I wanted to be able to cycle in their own methods. I ended up wrapping the Start/Stop calls in a try/catch; it would throw an exception if I tried starting a service which was already running or stopping a service which had already stopped.

private void ResetIIS()

{

    StopService("W3SVC", 10);

    StartService("W3SVC", 15);

}

 

private void ResetStateServer()

{

    StopService("aspnet_state", 15);

    StartService("aspnet_state", 15);

}

 

public static void StopService(string serviceName, int timeoutSeconds)

{

    using (ServiceController controller = new ServiceController(serviceName))

    {

        try

        {

            controller.Stop();

            controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(timeoutSeconds));

        }

        catch (InvalidOperationException ex)

        {

            // Service may already be stopped

        }

    }           

}

 

public static void StartService(string serviceName, int timeoutSeconds)

{

    using (ServiceController controller = new ServiceController(serviceName))

    {

        try

        {

            controller.Start();

            controller.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(timeoutSeconds));

        }

        catch (InvalidOperationException ex)

        {

            // Service may already be running

        }   

    }           

}

 

private void ListServices()

{

    ServiceController[] services = ServiceController.GetServices();

    foreach (ServiceController service in services)

    {

        string name = service.DisplayName + " : " + service.ServiceName;

        Console.WriteLine(name);

        //name.Dump();

    }

}


Links:

http://www.linqpad.net


 
Categories: .NET | C#

Extension methods were added as a new compiler feature in .NET 3.5. More specifically, that means you can use VS 2008 to use an extension method and then use VS's multi-targeting to run it under .NET 2.0. They're basically a means of tacking on methods onto existing classes or interfaces w/o actually needed to subclass or modify an interface. It's used extensively by (and added because of) LINQ. The methods aren't really part of the class, but the way you use them (and the way they appear in intellisense) make them feel like they're now part of the class. They're essentially static methods scoped to a specific interface or class.

I've been playing around with them a bit and ran into a case where I thought they'd be kind of a cool fit. I've needed to be able to convert a datatable into a comma-delimited file (CSV) so it can easily be opening in something like Excel, or pretty much anything that understands CSV files. I could create a separate class to do this, but it seems like this should be part of the DataTable class. To write an extension method you basically create a static method in a static class and prefix the first parameter with "this". Yep, that's about it.

I wanted it to basically work like this:

DataTable table = myBizObj.DataSet.Tables["SomeTable"];
string csv = table.ToCSV();

Creating the CSV is pretty straightforward - I loop through the column headers to generate the first header row, then I loop through each row in the table, then each item in the ItemArray of the row. I specifically decided to use quotes as delimiters around everything to keep it simple - the rules as to when you can/should include quotes for a CSV are pretty complicated. The only thing I do is escape out embedded quotes in the data by doubling them, ex. " becomes "". As soon as I had it working, I decided to create a few more overloads to let me control whether a header row was required, and the actual delimiter used (ex. instead of comma you could change it to a | pipe for example). Their is some example code in the XML help at the top of the class. In addition, I'm actually using this for a web page so it might be helpful to see what that code looks like:

string results = act.DataSet.Tables[tableName].ToCSV();

string mimeType = RCSSolutions.Web.Utility.DetermineMimeType("csv");

Response.ContentType = mimeType;

Response.AddHeader("Content-Length", results.Length.ToString());

Response.AddHeader("Content-disposition",

                   string.Format("attachment;filename={0}", "DelimitedList.CSV"));

Response.Write(results);

Response.End();

I'm calling out to another helper class which returns the mime type - in this case, all it does is return "application/csv". The above code basically pops open a dialog box with the file name filled in the browser on the client side.

using System;

using System.Collections.Generic;

using System.Data;

using System.Linq;

using System.Text;

 

namespace RCSSolutions.Utility

{

    /// <summary>

    /// <para>Various extension methods.</para>

    /// </summary>

    /// Sample of using ToCSV

    /// <example>

    /// DataTable table = dv.Table;

    /// // Assumes table is a DataTable

    /// string result = table.ToCSV(true);

    /// System.IO.File.WriteAllText(@"C:\sample.csv", result);

    /// System.Diagnostics.Process proc = new System.Diagnostics.Process();

    /// proc.StartInfo.FileName = @"C:\sample.csv";

    /// proc.StartInfo.UseShellExecute = true;

    /// proc.Start();

    /// </example>

    public static class Extensions

    {       

        /// <summary>

        /// Converts the passed in data table to a CSV-style string.      

        /// </summary>

        /// <param name="table">Table to convert</param>

        /// <returns>Resulting CSV-style string</returns>

        public static string ToCSV(this DataTable table)

        {

            return ToCSV(table, ",", true);

        }

 

        /// <summary>

        /// Converts the passed in data table to a CSV-style string.

        /// </summary>

        /// <param name="table">Table to convert</param>

        /// <param name="includeHeader">true - include headers<br/>

        /// false - do not include header column</param>

        /// <returns>Resulting CSV-style string</returns>

        public static string ToCSV(this DataTable table, bool includeHeader)

        {

            return ToCSV(table, ",", includeHeader);

        }

 

        /// <summary>

        /// Converts the passed in data table to a CSV-style string.

        /// </summary>

        /// <param name="table">Table to convert</param>

        /// <param name="delimiter">Delimiter used to separate fields</param>

        /// <param name="includeHeader">true - include headers<br/>

        /// false - do not include header column</param>

        /// <returns>Resulting CSV-style string</returns>

        public static string ToCSV(this DataTable table, string delimiter, bool includeHeader)

        {

            StringBuilder result = new StringBuilder();

 

            if (includeHeader)

            {

                foreach (DataColumn column in table.Columns)

                {

                    result.Append(column.ColumnName);

                    result.Append(delimiter);

                }

 

                result.Remove(--result.Length, 0);

                result.Append(Environment.NewLine);

            }

 

            foreach (DataRow row in table.Rows)

            {

                foreach (object item in row.ItemArray)

                {

                    if (item is System.DBNull)

                        result.Append(delimiter);

                    else

                    {

                        string itemAsString = item.ToString();

                        // Double up all embedded double quotes

                        itemAsString = itemAsString.Replace("\"", "\"\"");

 

                        // To keep things simple, always delimit with double-quotes

                        // so we don't have to determine in which cases they're necessary

                        // and which cases they're not.

                        itemAsString = "\"" + itemAsString + "\"";

 

                        result.Append(itemAsString + delimiter);

                    }

                }

 

                result.Remove(--result.Length, 0);

                result.Append(Environment.NewLine);

            }

 

            return result.ToString();

        }

    }

}


 
Categories: .NET | C#

I recently added a maintenance form to our website which allows a user to add and delete entries to a list of banner ads stored in a simple XML file. Previously we've just been maintaining them manually by editing the XML directly and copying the associated banner images into a folder on the website. When you delete an ad, I decided to NOT delete the associated image since they may be reused (and I wanted to avoid forcing the user to upload the image again). However, we'd still like to periodically clean out this folder and "archive" the images so they're not cluttering up the selection screen.

I basically needed some code which would get me a list of files in the banner images folder which were not referenced in my banner XML file. It can be kind of clunky to iterate through XML but they've made it much easier with the introduction of LINQ. I fired up LINQPad (which, BTW, is an AWESOME free tool for testing out LINQ code) and tried out a few ideas. As a side note, it looks like Intellisense is now available if you purchase a copy of LINQPad.

http://www.linqpad.net/

I started with querying the filesystem to get a list of files:

  

DirectoryInfo info = new DirectoryInfo(@"X:\inetpub\wwwroot\images\banner");

FileInfo[] files = info.GetFiles();

 

files.Dump();

 

.Dump() is an extension method available in LINQPad which dumps out the results of the query (we haven't actually used LINQ yet to do anything).

Here's what it looks like:

FileInfoLinq

You might notice that Directory contains a DirectyInfo element. If you click on the down arrow it will expand out these values as well.

So I now had a list of files, I wanted to then get a list of images referenced in my banner file. Here's the format of the XML file:

<News>   
   <NewsItem>
       <Title>Supertooth3-banner.gif</Title>
       <Image>/images/banner/Supertooth3-banner.gif</Image>
       <Height>183</Height>
       <Link>/PortalView.aspx?navto=/Supertooth3-banner.gif</Link>
       <Date>July, 19th, 2003</Date>
       <Target></Target>
   </NewsItem>   

  

 

I haven't really been using Title for anything besides the name of the image file, so I was able to take a bit of a shortcut here and use it for my comparison. To pull out the list of images used in the XML, I wrote this query:

XDocument doc = System.Xml.Linq.XDocument.Load(@"X:\inetpub\wwwroot\adv.xml");

doc.Dump();

 

var news = from item in doc.Descendants("Title")

           orderby item.Value

           select item.Value;

news.Dump();

 

Which produces this:

XmlTitlesLinq

I noticed that the banner images folder contained a bunch of other files that I really didn't want to consider for filtering, so I needed to narrow my query to files that had specific extensions. C# doesn't really have a direct equivalent for INLIST, but we can do this a slightly different way for the same effect.

First I define an array of valid extensions, then (inside the where clause of the LINQ query) I check to see if this list of file types contains the filetype of the file I'm currently evaluating. It's a bit backwards, but it's simple and it works.

string[] fileTypes = { ".jpg", ".gif", ".png" };

var imgFiles = from file in files

               where (fileTypes.Contains(file.Extension))

               orderby file.Name

               select file.Name;

 

imgFiles.Dump();

 

Now I've got a list of files from my XML and a list of files from the banner images folder. I want to get a list of files from the banner images folder that aren't in the XML list. I do this via a final query:

var extra = from singleFile in imgFiles

            where !(news.Contains(singleFile))

            select singleFile;

extra.Dump();   

This returns my extra files. Now I can just use this list to move my images into an archive folder periodically.

If I put it all together, I end up with this:

 

XDocument doc = System.Xml.Linq.XDocument.Load(@"X:\inetpub\wwwroot\adv.xml");

DirectoryInfo info = new DirectoryInfo(@"X:\inetpub\wwwroot\images\banner");

FileInfo[] files = info.GetFiles();

doc.Dump();

files.Dump();

 

var news = from item in doc.Descendants("Title")

           orderby item.Value

           select item.Value;

news.Dump();

string[] fileTypes = { ".jpg", ".gif", ".png" };

var imgFiles = from file in files

               where (fileTypes.Contains(file.Extension))

               orderby file.Name

               select file.Name;

 

imgFiles.Dump();

 

var extra = from singleFile in imgFiles

            where !(news.Contains(singleFile))

            select singleFile;

extra.Dump();   

Links:

http://www.linqpad.net/


 
Categories: .NET | C# | LINQ

August 12, 2008
@ 10:17 PM

I ran across a really cool .NET library on a recent project I've been working on. We have an internal website where we post news, documentation, etc. - basically a Content Management System (CMS). We're working on a new set of documentation that is being done inside of a third party help builder application. We need to import the HTML files it generates into our website (so we get all the things it offers, like security, searching, revision tracking, view statistics, etc.). So basically, I need to run through a lot of HTML files, build a tree of the documents (similar to the help file) and rewrite all of the URL's and image links to point to the correct URL inside of the site. I initially started looking at various regular expressions that I might be able to use over at http://regexlib.com/. Almost every single one of them had some comment about it failing under some circumstances. The HTML is surprisingly clean, but I was still nervous about it. So I looked at using GOLD to parse the HTML. However, from some of the comments I found it still didn't make everything as easy I would have liked. I finally ran across HtmlAgilityPack over on CodePlex . It's a .NET library which lets you read AND write changes to an HTML file via a simple API.

Here's a chunk of code from my importer so you can get a feel for how it works:

HtmlDocument doc = new HtmlDocument();

doc.Load(content.FullDocumentPath);

HtmlNodeCollection linkNodes = doc.DocumentNode.SelectNodes("//a/@href");

 

Content match = null;

// Run only if there are links in the document.

if (linkNodes != null)

{

    // Fix up the URL's

    foreach (HtmlNode linkNode in linkNodes)

    {

        HtmlAttribute attrib = linkNode.Attributes["href"];

        // If it's an internal page anchor, ignore it

        if (attrib.Value.StartsWith("#"))

            continue;

 

        string path = this.GetAbsolutePath(content.DocumentLink, attrib.Value);

        match = this.m_contentList.Find(p => p.DocumentLink == path);

 

        if (match != null)

            attrib.Value = match.GetUrl();

        else if (!path.ToLower().StartsWith("http://") && !path.ToLower().StartsWith("mailto:"))

            Console.WriteLine("Cannot find matching document, searched for " + path);                       

    }

}

 

Basically, doc.DocumentNode.SelectNodes("//a/@href") returns a collection of links in the document (it uses XPath syntax for the selection string). From there, I just iterate through them, build the new URL, then save the modified Url via code that just does: linkNode.Attributes["href"].Value = "New URL Here". I also needed to strip out all the script tags inside of the document, so it uses similar syntax:

private void StripOutScripts(HtmlDocument doc)

{

    // Strip out the scripts

    HtmlNodeCollection scriptNodes = doc.DocumentNode.SelectNodes("//script");

    if (scriptNodes != null)

    {

        foreach (HtmlNode scriptNode in scriptNodes)

        {

            scriptNode.ParentNode.RemoveChild(scriptNode, false);

        }

    }

}

 

I do the same sort of thing - iterate over the collection, except this time tell it to remove the nodes from the document (note that I'm grabbing the parent node, since the current node is everything contained within the script, excluding the <script> tags. By getting the parent, we get that and the tags themselves.

Each collection has a WriteContentTo() method which can write the HTML for that section of the document to a Stream. What's really nice about this entire library (besides how simple it was to use) was the fact that it doesn't seem to mangle the existing HTML when using WriteContentTo() (at least from what I've seen). Only one minor complaint - the docs are a bit weak. It just includes the standard documentation of the classes, not much in the way of examples. However, it's pretty consistent so it doesn't take much to get started with it.

What a great library - it couldn't be simpler. It saved me a ton of time.

Links:

http://www.codeplex.com/htmlagilitypack
http://regexlib.com/
http://www.devincook.com/goldparser/


 
Categories: .NET | C# | Developer Tools

November 14, 2007
@ 10:11 PM

This falls into the "hey, I didn't realize this was available" category. In the 2.0 version of the .NET framework, support was added for nullable types, I'm guessing primarily for improved interaction with databases. Previously, nulls were a real pain to deal with; now they're only a bit more work (the pains not completely gone, but it's not as bad anymore). Lets say you've got a date time field in your database, it can have an actual date filled in or it can be null. In prior versions, you had to rely on "magic" dates to do translations when loading and saving your data (eg. 1/1/1900 is really null). Now you can just define a nullable type by prefixing the type with a question mark ?

 

DateTime? activeStart = (DateTime?)row["ActiveStart"];

 

That's not the point of this post though. They've added a nice operator ?? - so let's suppose I've got a calendar control that returns null if no date has been selected. I'd like to default to the current date if that's the case. I can write code like this:

 

DateTime start = System.DateTime.Now;

if (this.startCalendar.SelectedDate != null)
   start = this.startCalendar.SelectedDate;

 

Or I can use the ?? operator:

 

DateTime start = this.startCalendar.SelectedDate ?? DateTime.Now;

 

That's much simpler code to understand (at least to me). I like this a bit better than the normal ternary "if" support, which I always find a bit difficult to read:

string sample = a==b ? "A=B" : "A<>B" 

Maybe it will grow on me eventually...
 
Categories: C#