You have reached the blog of Keith Elder. Thank you for visiting! Feel free to click the twitter icon to the right and follow me on twitter.

Using Regular Expressions in C# vs PHP

Posted by Keith Elder | Posted in .Net, PHP | Posted on 05-12-2007


Recently at work I made a call out to all of the engineers to send me code they thought should be placed in the common library for .Net development.  In one of the responses I got an email from a PHP developer that shared a regular expression to check the format of money.  He stated he didn’t know how often we use them (referring to regular expressions) in C# but he thought he’d pass it along anyway.  That got me to thinking.  Do I use regular expressions as much in C# as I did in PHP? 

For those that are curious, the regular expression that was sent over works perfectly well in C#, no problems.  I think developers will find regular expressions will easily move from one to another.  If you happen to be porting PHP regular expressions to C# and vice versa you shouldn’t run into too many problems.  For example here is a quick test I threw together with the regular expression to make sure it worked.

using System;
using System.Text.RegularExpressions;

class Money
    public static void Main()
        Regex exp = new Regex(@"^[1-9][0-9]{0,2}(,{0,1}[0-9]{3})*(\.[0-9]{0,2})$");

When complied and ran it yielded the following result:


It worked.  When it comes to regular expressions within C# I have used them.  I find they are more like pepper sprinkled in a good stew rather than a main course meal.  That is how I would state the difference in use of them between the two languages.  If I had to give a percentage of how much less I use regular expressions I would definitely say more than half as much, and maybe go higher to 90% depending on the situation.  Why? 

I think it boils down to the reason that C# is strongly typed and PHP is loosely typed.  For example, the following code could never be written in C#. 

$x = 1;
$y = '2keith';

echo $x + $y;  // will print 3 (yes you can add strings and numbers in php)
// set $x to something completely different
$x = array('a', 'b', 'c', 'd');

echo $x[1]; // will print b
Running the entire thing will result in:  3b

To some this example may be scary, others may look at it as a feature.  Whichever way you think, most developers when asked what the result will provide respond with all sorts of various answers.  When I taught PHP classes as a consultant I would use a similar example with the class.  To no exception, no one could ever predict the out come.  Answers given ranged from, it should throw an exception since you can’t add a string and a number.  Or it should throw an exception because the variable $x was reassigned to a different type.  

Do you see “why” PHP code relies on regular expressions more now?  Since $x can literally become any type at any time, a PHP developer can never rely on the fact that $x is an INT.  About the only way to check that value is the use of a regular expression.  In the PHP world it is called Type Juggling.  Conversely in C#, once the variable x is assigned a type, it cannot be changed and only valid numbers can be assigned to that type therefore eliminating the need to use a regular expression to check the value of the variable.

The question then becomes though, is this the C# way to test for the money value?  I would probably argue it isn’t the “best” way to handle money in C#.  While it certainly works there are other things to take into consideration when adding money.  For example two different types of money such as US Dollars and Euros cannot be added together.  It must first be exchanged and then added.  The same thing could be said of other operators performed against a variable of type money.  This is where it would be suitable to use a struct and create a new type called Money.

We can in C# declare a variable as the type of decimal and use it as money if we choose.  In this case we still don’t need a regular expression to validate the value of our variable.  Here’s a sample showing one way to handle a rogue value:

            decimal money;
            if (Decimal.TryParse("123.a234", out money))
                Console.WriteLine("money is valid");
                Console.WriteLine("money is invalid");

I suspect a lot of programmers use this method but again a struct is more desirable.  Andre de Cavaignac has a great example of building a struct for a money type.  He provides these examples:

            Money eur10 = new Money(MoneyCurrency.Euro, 10);
            Money eurNeg10 = new Money(MoneyCurrency.USDollar, -10);
            Money usd10 = new Money(MoneyCurrency.USDollar, 10);
            Money usdZero = new Money(MoneyCurrency.USDollar, 0);

            bool result = (eur10 == usd10); // returns false;
            bool result = (eur10 > usd10); // throws InvalidOperationException (comparison not valid)
            bool result = (eur10 > Money.Zero); // returns true
            bool result = (eur10 > usd0); // returns true
            bool result = (usd10 > eurNeg10); // returns true (positive always greater than negative)

Obviously he’s put a lot of thought into how money should be handled and if you look at his library you’ll see he accounts for all different type of currencies. 

For those wondering the differences about regular expressions in PHP and C# I hope that gives you some insight into how the different languages respectively handle different situations.  It all boils down to strong typing vs loose typing and the ability to create new types based on structs.  Happy Holidays!

Open Source to .Net Transition – Mac or PC?

Posted by Keith Elder | Posted in .Net, Linux, Open Source, PHP | Posted on 23-10-2007


It seems that an article I wrote a while back is making its way around the Internet once again.  It never fails that once a year or every 6 months it pokes it’s head up from the ashes, dusts itself off and finds new readers.  The article I’m talking about is this one:

How an Open Source Developer Transitioned to .Net

It is an interesting read and if you haven’t read it, check it out.

I started getting lots of emails from readers last night and this morning as the article was passed around.  One person emailed me a question that was particular interesting after reading it:

Thanks for sharing your story on your transition from .php to .net. My main question is; did you also change from working on Macs to the inferior PC’s?

Obviously by the reference of “inferior PC’s” in the question we know where this reader stands.  It is sort of like one of those interview questions you get that is completely loaded.  For example, “So Mr. Person Wanting a Job…. things around here are really busy.  A lot of the times you have to switch tasks very quickly.  How would it make you feel if you were working on a project and then your manager asked you to stop it and move onto something else?”  Obviously the question has already been answered.  Or rather loaded up for you to respond in the way the person asking the question wants to hear.  By the way, if you ask these type of interview questions, stop.  They get you no where.  I digress though. 

I don’t know if this question is the same loaded type of question but my first reaction was, wait, aren’t Macs made up of the same parts that are in PCs?  It is a hard drive, processor, video card and memory.  Apple looks at various vendors and plugs in the best deal / bang for the buck just like any other PC manufacturer.  Are PCs really inferior just because Apple has a better looking plastic cover than most PCs?  I don’t think so since they are essentially made up of the same parts.  Case in point I recently upgraded the wife from an aging iBook to a HP notebook.  I think she got a far superior product for a whole lot less money compared to a Mac.  That’s another post that I’m working on though. 

Maybe he was talking about the PC operating system being inferior?  What if I am running FreeBSD on my PC, does that make it more superior to the Mac since OS X is really just FreeBSD under-the-hood?  Or what if I’m running an Intel version of BEOS?  Maybe it was a OS X vs Windows comment?  The reader didn’t say so I am totally speculating on what he’s “really” trying to ask and also infer.

Here is the bottom line folks.  When you chose a technology you ultimately chose a platform.  We all do it and to say we don’t is just wrong.  When I was writing PHP/MySQL I used Linux for years since I thought it was important to develop applications on the same OS the application was going to run on the server.  I knew the Linux platform inside and out.  Even enough to teach it at the college level.  Today I write .Net code and I write that on Windows for Windows.  Again, I think it is important to write software on the same platform it is going to run on.  The difference is when you chose .Net you are married to the Windows platform, at least today.

Whether you want it to be or not, there is a huge platform investment made as a developer to understand the full potential of our applications.  I have a buddy at work that has been doing Windows IT infrastructure related stuff for years.  He understands a lot of things under the hood of Windows that I don’t even understand.  For me he is a resource I use often to pick his brain to solve a problem.  More times than not, he has an easier way to solve a problem than I was thinking just because he knows the platform.   For .Net development it means that those of us doing .Net development are married to the platform of Windows.  That is not a bad thing though since from a business standpoint the platform as a whole provides a lot of value.  

Yes, I use PCs today as opposed to Macs.  I’d be completely non-productive and probably lacking brain cells to development enterprise applications on a Mac and boot Visual Studio in a virtual machine.  I’d also be completely non-productive trying to write .Net code using Mono with VI.   I’ve seen lots of Macs at conferences and even friends of mine that are fellow MVPs have purchased Macs and run Visual Studio in a VM or just run Windows on the Mac 100% of the time because they like the Apple notebook better.   For those running Windows on an Apple, if you want to pay the Apple tax and spend a lot more money for your shiny toy fine, at least you understand that you are ultimately writing .Net on Windows.   For those that boot virtual machines and do .Net development God bless you, you must have the patience of Job.  I’ve done it and ultimately I came to the conclusion of:  Damn this slow and non-productive.  BTW, if you are a client of a consultant and he/she walks in with a Mac and is doing .Net development for you.  Run!  They just doubled your billable hours haha!  I poke fun in jest obviously but hey, it is something to think about if you are footing the bill no?

The thing is I still like OS X.  Notice I didn’t say Apple, because I don’t like the Apple hardware tax having built computers for years.  The operating system I like, nay, completely admire still to this day.  I’ve spent many hours looking at XCode on Mac OS X wishing it could be my development platform of choice.  Wishfully thinking that I could get a job as an Enterprise OS X developer at one time.  I wrote a few programs for Mac OS X and found it to be 5-10 steps and way more complicated than it needed to be just to do something simple like put a button on a form using Cocoa.  Compared to Visual Studio dragging and dropping a button onto a form and double clicking to wire up an event is apples and oranges (pun intended).  I’m sorry, but Apple spends all their time on making their OS shiny and adding features for end users but doesn’t do a damn thing to help developers embrace their platform at all.  At least that is how I see it.  If you don’t agree, then feel free to shine some light on my short sightedness, I’m all ears.

So yes, I use PCs today, not a Mac, and I don’t feel when I wake up in the morning and sit down at my computer I’m using an inferior product.  As a matter of fact I feel I have more options using the Windows Platform than I do using a Mac, especially since there isn’t an Apple store within 300 miles from me.  Not only that but professionally I have all sorts of nice haves that run and are supported with the Windows platform such as integrated authentication for applications, SQL Server, Biztalk, Windows Presentation Foundation, Winforms, Asp.Net, Windows Communication Foundation, Workflow Foundation, Silverlight, Visual Studio, Ado.Net, Windows Mobile, Office (Word, Powerpoint, Excel, Infopath, Publisher), Sharepoint, built-in analysis and data mining features, OLAP, Report Services and much more.  Based on all of that reader, which platform seems inferior now?


How an open source developer transitioned to .Net

Posted by Keith Elder | Posted in .Net, Asp.Net, Open Source, PHP, Programming | Posted on 11-03-2006


For a long time I’ve been wanting to put this together.  A lot of my friends who were open source advocates like myself are perplexed with my transition to what they call the “Dark Side” of development.  Referring of course to Microsoft as the evil empire.  I took some time this morning to finish how and why I migrated from programming mainly in PHP to .Net.  I didn’t want to put this information into a blog post because as I was writing it, it just didn’t feel right so I created an article out of it.  In order to give you the full picture I give some information on my background to cement how firmly planted I was in open source technologies.  Then I give you some of my thoughts on the conversion process.  In the end, I give some advice for others that might be curious as how to make this conversion.  

Read the article “How An Open Source Developer Transitioned to .Net”



Scaling PHP

Posted by Keith Elder | Posted in Open Source, PHP, Programming | Posted on 24-05-2004


I found a really good article which outlines some nice tips to scaling PHP. The article is written by George Schlossnagle. In his article he explains why you do not need large DB abstraction layers like PEAR and ADODB and why you should NEVER use relative paths to images. The article can be found here.

LogiCreate Application Server Open Sourced

Posted by Keith Elder | Posted in Open Source, PHP, Programming | Posted on 07-06-2003


The LogiCreate Applicaton Server built with PHP was released as open source on June 5th, 2003. LogiCreate is a framework to build portals, CMS, CRM or custom web applications. It is extremely fast to start developing applications with, very little code for the developer to start writing and is extremely different from pretty much anything else out there right now. You can download the PDF presentation on the LogiCreate site as well as register on the site to download the system. We’ve been using it for several years now and will start offering hosting accounts pre-packaged with it soon.