Brendan Enrick

Daily Software Development

Static Methods and Interfaces in C#

Someone just commented on my C# interfaces article on ASP Alliance asking an interesting question, and I figure I will respond to it here since I can give a better response here. I don't want to clutter the article comments. Also I can add nifty cool pictures, format all of my text nicely, and write a heck of a lot more here.

This is the excellent question I was asked.

All my classes implementing my interface should have a static funtion.
Why can't I have a static function in an interface???


This is how I responded in the article.

One important thing to understand about static methods is that they don't really need to be tied to classes. Static methods basically just exist for convenience.
An interface is as the name says an interface to something. Think of it like an automobile interface. There are defined ways of working with the car. They have a steering wheel a gas pedal and brakes. An interface defines that and all automobiles will have those, but an interface doesn't define anything about "cars in general" (static) it defines what will be the interface for individual cars (instances).

As I was saying interfaces are used for defining interfaces for code. I like my car analogy, but I think I'll use a sail boat analogy this time.

Think of writing an interface in C# called ISailable. This objects implementing this interface will be sailboats. So what does every sailboat need to be able to function. For simplicity I'll say that we just need to have sails and a wheel. All sailboats will also need to be able to sail. So now we've defined how our ISailable objects work. We can now create sailboats using this nice interface. Notice we haven't defined how large the sails are or what style of sails. We just said we need sails. We also did not define the wheel. Is it metal or wood? How large is it? We don't care in the interface the classes implementing the interface will each define those differently. Notice that different boats have very different types of sails.

We might define out ISailable interface in the following way. Keep in mind I am using a lot of simplicity here.

namespace Enrick.Interfaces
    public interface ISailable
        void Sail(string destination);
        void Steer(string direction);
        void RaiseSails();
        void LowerSails();

Then once we have that defined we are able to implement the interface and create our first sailable object which will of course be a sailboat.

namespace Enrick.Boats
    public class SailBoat : Enrick.Interfaces.ISailable
        #region ISailable Members

        public void Sail(string destination)
            // Write sailing logic here. It should be specific to this type of boat.

        public void Steer(string direction)
            // Write steering logic here for this exact type of boat.

        public void RaiseSails()
            // Write logic to raise these specific sails here.

        public void LowerSails()
            // Write logic to lower these specific sails here.


Static interfaces do not really apply to what we've defined though. We've just been talking about how to interface with individual sail boats. We haven't gotten to static methods really. This is because static methods aren't really necessary. Many languages have them, but they could just as easily be outside of the class and have the same functionality. Static methods are by definition methods which aren't specific to individual instances of classes. This means we could define these methods anywhere and achieve equivalent functionality. They also don't really apply with interfaces and the C# language specification doesn't allow static methods on interfaces because they don't really make sense with interfaces.

There are circumstances where someone might want to have a static method on an interface. Perhaps the static method was going to be a way of performing an action on an entire collection of the instances of the objects. Perhaps you have a fleet of ISailable ships that you will want to sail together. This would make sense to have a static method which would be associated with the class, but it isn't necessary. Instead we will create a static method elsewhere. It will not be tied to our interface. We can have it take a list of ISailable objects and then it can perform the sailing operation of our fleet.

public void SailFleet(List<ISailable> fleet, string direction)
    foreach (ISailable boat in fleet)

Notice here that I've defined a method which might have been static before on each of the boats and each one would have take a List of their instances, but that would be silly. This solution allows us to have methods which work with ISailable objects but they need not be defined as requiring an interface. Sadly there is not a way of having static methods on interfaces in C#.

I hope that answers some questions. As always, thanks for reading!

w00t! The Word of the Year is Awesome

Yes, you read that correctly, because Merriam-Webster's Word of the Year is w00t. Most of you have probably heard this interjection often exclaimed by geeks winning some sort of competition usually a multiplayer game. I know not where the word originated. I would assume an online computer game. Perhaps counter strike. I am quite impressed that Merriam-Webster would allow w00t into the contest. I would venture a guess that it is the only word in the competition which uses numbers and letters. Perhaps this is the beginning of a deluge of changes in the English language. The Internet has spawned changes faster than could probably have been imagined in the past. It takes writing over time for a written language to change, but the vast amount of writing which occurs every day on the Internet is an extreme. I expect we'll be seeing far more changes to the language we love in the next few years. What word will be next on the list. I can only wait and hope for 1337. Perhaps it will be next year's word of the year. It lacks letters completely, and overcoming that hindrance will surely pave the way for future Internet-based words.

w00t Merriam-Webster !5 1337!!!!1!

Great Conditional Logic

It is amazing some of the relics that can be found while code reviewing old code. Sometimes developers do things without thinking and make some great code. I am of course referring to some really funny code such as what I found a few minutes ago. I am always annoyed when boolean values are checked explicitly in conditional statements like the following code.

if (IsValid == true)

This bothers me because the true is completely useless. I would read this code as "If is valid is true", and that is kind of silly when I could say "If is valid".

if (IsValid)

This is just part of the annoyance in the code. Now I've cleaned it up a bit here, because it didn't really have a variable named IsValid. It was actually a variable named edit. We were not sure if edit meant that someone was allowed to edit or if it was in edit mode or what.

This was just slightly annoying. The really amazing part was in the else of this if statement. It had a great bit of else if logic. The code looked overall like this.

if (edit == true)
    // Lines of code here
else if (edit == false)
    // Lines of code here

I now wonder what possible other condition is there? In the else is there another state for edit? It is not a reference type, it is a value type so it can never be null. Just got to be careful of boolean operators there are so many other values for them other than true and false.

I hope everyone enjoyed this fun little code snippet.

Little Bobby Tables

One web comic I commonly read is xkcd. It is a great comic that has a lot of good computer as well as just nerdy jokes. It has a great comic about SQL injection attacks and why you need to sanitize your database inputs. This is a lesson in what to not name your child.

I hope that everyone who reads this gets this joke. Quite amazing. This comic is full of great stuff like this. Try to not waste your day reading this grade A material.

A New Face for RegExLib


With some recent efforts from an excellent designer named Craig Palenshus, everyone's favorite regular expression library has received a nice visual upgrade. You'll notice the site is much cleaner and more presentable now. The overall design is excellent IMHO. The site seems to be much easier to use and navigate. The links are more clearly defined and laid out. The page is not quite so cluttered. In the past the site had been added to and altered plenty of times, and this created layers of clutter and bad layouts. Steve Smith and I have taken some time to fix some of the bugs from the previous system as well as getting some of Craig's alterations functioning well.

A long time ago on web site far, far away there was a regular expression tester that worked pretty well. Since then the client side tester broke, but no one really had the time to fix it. With the advent of the new look for the site soon coming, it was important to make sure that all aspects were functioning within the operational standards. One man, Brendan Enrick, set out on an adventure to complete the regular expression tester. It received an overhaul from its previous design. It not only works as it previously did, but the client side testing seems to functioning once again within normal parameters.

Ok so in all seriousness, I fixed up the regular expression tester on RegExLib. Let me know if you find any bugs or problems with it, and I'll see what I can do to clean them up. I hope you enjoy the new layout of that page. It worked pretty well for me. I've used it a bunch of times since I updated it. I find it a lot easier to use. I hope you feel the same way.

RegExLib has come a long way since Steve Smith first created the site in ASP.NET 1.0, and it has seen a couple of big layout changes. The first incarnation of RegExLib was red. The site has been green for the past few years, and it is staying that way for its new look.

This is how the site looked near its first incarnation. This is the site back in 2003 when it was still wide and red. It was originally part of ASPSmith. This is the first view of the library as its own web site. As you will notice it was reasonably well designed. The basic layout of the site is nice. The search results aren't very clean, but they work for their purpose.


Later the site received a new design of Thomas Johansen. That layout remained for plenty of years, and it received many minor changes over the years of use. This is the nice green layout everyone has been seeing for years. 


Now after trimming the fat off of the site, it is a tall, lean page with plenty to offer its users. Sections of the pages are grouped together nicely with headings. There is spacing to allow users to clearly see and use elements on the page. The RSS feed is being powered by FeedBurner so you can now see how many others are subscribing to the regular expressions on the site.


The site is more usable in my opinion. I have a much easier time reading and working with the pages on the site. I think this visual upgrade is also a very strong usability upgrade as well. I recommend you check out the new design of RegExLib.

Let us know what you think!

Unpacking Tuples in Python

There are plenty of reasons why I like the Python language. Yes, I know it is an interpreted language and it is very dynamic. While looking at some JavaScript mere moments ago, I saw someone pass back two values from a function. This is one thing that bothers me when I am writing in a lot of languages. I will need to pass back two or more values from my function. So I need to change the return value to some type of a sequence perhaps an array. Then I need to adjust the location where I call the function so that it accepts and array. It then needs to take each value of the array and place the returned value into each variable that needs the value.... Yuck! What a pain just to get a couple of values!

A lot of times I just want a simple solution to my problem. I'd like to type 2 lines of code instead of 5. Python has plenty of problems, but one of my favorites assets of the Python language is the ability to Unpack tuples from functions. So lets say that I want to return three values from my function. I just separate them by commas and it works. I then in my function call just list each variable to which those values correspond separated by commas and away I go.


def GetBestHotel()
    # Logic Goes Here
    return name, location, cost

hotelName, hotelLocation, hotelCost = GetBestHotel()


Isn't that a neat trick. I just listed each variable and Python unpacked that tuple (basically an array) and it put each of the values in the correct variables. No extra variable declarations and I didn't have to have an assignment statement for each of the values being returned. Now that is convenience. This is obviously a very specialized little feature, but I do enjoy having it available. It is always good to know of the useful tricks of any language you use.

An Explanation of Interfaces in C# for Beginners

I recently authored an article for ASP Alliance in which I describe the basics of how interfaces work and how to use and create them in C#. I tried not to describe in great detail exactly how everything works, because that will prevent beginners from understanding how interfaces may be used. I plan to write further about this topic, but I think it a mistake to begin with even an intermediate description of a topic without at least giving a beginners explanation first. I'll be doing some more advanced examples for my next article on interfaces, so look forward to one in the not too distant future.

I am not sure how the rest of you feel, but I think that interfaces are an amazing tool. I try to use interfaces when possible, because it makes code much more maintainable.

Let me know what you think and any suggestions for future articles.

As always, thanks for reading!

Using the as Statement to Cast Without Exceptions in C#

It is common to obtain variables with a type which is not the desired one. Considering that plenty of times there will be variables passed using the object data type, it is important to be able to cast your variables into more usable types. Say for example you're passed a variable as an object. You probably want to be able to access properties or methods of this object, so you will need to cast it into another class. The simple way of doing this is to use code similar to this.

DataTable myData = (DataTable)dataSource;

This works well, but is slightly more dangerous than it needs to be. The problem I have with casting it in this way is that the variable dataSource might not be a DataTable, and if this is the case we will throw an exception. Yes, we could wrap a try-catch block around this code, but I prefer to avoid exceptions when possible instead of catching them.

If we use the as statement we will be able to achieve the same result and just need a little bit of checking for an error. This way if our code is in an exceptional case we can handle it ourselves instead of having the overhead of a try-catch block. If the as statement receives an invalid cast it does not throw an exception. Instead of throwing the exception it merely places the null value instead. Since we receive the null value if the cast fails, we are now able to simply check for the null value.

DataTable myData = dataSource as DataTable;
if (myData != null)
    // Perform work here
    // Error handling code goes here. Perhaps a message of some kind.

As you can see we're able to avoid our exception and handle it without using a try-catch block. I am not advocating programs without these try-catch blocks. I am merely saying that I find it better to avoid catching exceptions that could have been avoided in the first place. I think some people become excessive with try-catch blocks. I've seen plenty of people write code which doesn't check strings for validity they instead just try working with them and if an exception occurs they catch it and respond. I think it is simply crazy.

Have a great day! Happy casting!

Copying Data From SQL Server Management Studio

I often write queries in SQL Server Management Studio to find different bits of information about which I am curious. This is quite easy and I discover a lot of useful and interesting things this way. You might ask why I am writing this blog post. I'll first say that I try to share these little tidbits with others. Sure I could bring people over to my computer and show them these nifty collections of data with certain meanings, but that would just be silly. I need to store it elsewhere and email it.

Maybe I'm just going about things the wrong way, but I've tried to copy and paste from SSMS into Outlook and that doesn't usually work well. Outlook doesn't seem to figure out that I would like my data pasted as a table, so I usually throw it into Excel first. Doing this will get my data into a nice tabular format.

Now that I've finally gotten my tabular data into a table everything is great. Right? No. I lose once again. I don't have the column names with my data so I end up with something like this and without column names people will not know what I am trying to tell them.

Brendan McAwesome Enrick 5555555555 12345 9876543
John Michael Smith 1234678910 1337 31337

So then I have to go and type out column names so that the people I send this to know what it is. Now for this example it wouldn't be too bad, but sometimes I'll be sending 10 columns worth of data and that is just annoying. I wish I could just copy out of SQL Server and have it pull column names at least then my Excel trick would at least work. If anyone knows a nice easy way to just copy out of SSMS please let me know it would make things so much easier.

Perhaps you can find some elusive option names similarly to Copy All Data With Column Names, because I sure as hell haven't found it.

In case you are wondering those column names are; FirstName, MiddleName, LastName, Phone, SomeValue, SomeOtherValue.

Knowing the Default Access Modifiers in C#

512px-PadlockI have a few friends in college who are learning C# on the side. I've been answering their questions when they ask. One interesting question was regarding access modifiers. I was asked which access modifiers are used by default in certain situations when there is not one specified.

First I'll quickly remind everyone of the access modifiers and what has permission to access them.

private - Any members of the same class have access.

protected - Any members of the same class or any derived class have access.

internal - All code in the same assembly. This means that it doesn't matter where the code is in the assembly. It can be in any class as long as it is inside of the same assembly it has access.


When you define a data type of some kind (class, struct, enum, etc.) you need not specify an access modifier, but be aware that the default will be internal. This means that anything else in the assembly has access to it. There is very little sense for it to be private, because that would mean that only it has access to itself which means it would never do anything. Since we like the default permission to be as restrictive as possible it makes sense that the default is internal.

large_gold_keyThe other code with access modifiers are the members of the types we were just discussing. Since these are within a type private makes sense for them, and since we like keeping this locked down by default they use the private access modifier if no other is specified. This means they are only accessible by other members of the same thing. So a class might have a private member function and that function can only be called by other members of the class; functions, properties, etc.

Protected is probably my favorite access modifier to use, but since it is less restrictive it is not the default. This is because pretty much any time protected can be used so can private so private will be the default. Public is just way to open to be the default and C# doesn't want to encourage programmers to have everything be public. That is just a bad way to write code.

Don't get locked out because you don't know the default access modifier. Make sure you key in to the correct way of writing your code.

Have fun writing code with access modifiers!