Converting Hex string to Int in C#

For a hex literal that’s not prefixed you can quite easily convert it using int.Parse in C#:

string hex = "142CBD";
// this returns 1322173
int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);

But as you’ve probably noticed, most hex literals are prefixed with 0x (e.g. “0x142CBD”) which would throw a FormatException if you try to parse it using the above code.

In order to parse a 0x prefixed hex literal you need to use the Convert.ToInt32(string value, int fromBase) method instead:

string prefixedHex = "0x142CBD";
// this works, and returns 1322173
int intValue = Convert.ToInt32(prefixedHex , 16);

Buzzword Buster – DDD

Definition:

Domain Driven Design (DDD) is an approach to software design which puts the focus on the problem domain and provides a structure for making design decisions to accelerates software development for complicated domains. The key components in DDD include:

Domain: the subject area to which your program is applied

Model: abstractions that describe aspects of a domain and can be used to solve problems related to that domain

Domain Experts: people with the most complete knowledge about the world your system will live in

Ubiquitous language: a language around the domain model used by all team members, the language is ubiquitous because it is present everywhere

Purpose:

Traditionally .Net applications are developed using a data-centric approach where you build your system around your understanding of the data – creating all the tables and the relationships in the Database and then mirror them in your .Net code. This approach is popular because of the ease and speed with which you can create a fully functional system from the ground up.

DDD on the other hand, focuses on the problem domain as a whole which covers not only the data but also the behaviour. DDD encourages greater involvement from domain experts, the idea is to build your system in a manner that’s reflective of the actual problem domain you are trying to solve and let the domain drive your design decisions.

One of the greatest challenges in developing a new system is to learn and understand the new business, which is why a single, shared language (the ubiquitous language) between the users and the developers can go a long way to reduce misinterpretations and create a more concise and effective communication amongst all interested parties.

Parting thoughts…

It is important to remember that whilst DDD is better than the data-centric approach in some cases, the reverse is also true.

Also, DDD carries with it the overhead on the developers’ part to become proficient (or sometimes experts!) in the problem domain and being able to communicate with the users in an common language.

Mastering both programming skills and business knowledge in the core problem domain is difficult and takes significantly longer than the course of developing an application – seasoned developers in the Financial sector would no doubt agree with this! This is one of the reasons why knowledge in a particular area (equities, derivatives, etc.) is such a valuable asset and developers who also qualify as domain experts in a business area are so highly sought after and compensated.

On the hand, it is also why so many find it hard to break into Finance despite boasting impressive development skills, and why many others become typecast with a specific industry/area and find opportunities outside their familiar territories hard to come by.

During my time with Credit Suisse I have come across many developers who have spent their entire professional career in the same business area, becoming domain experts in their own right. Though personally it’s not what I’m looking to get out of my career I can definitely see the merits of doing so and appreciate the enthusiasm they have for their problem domains.

Further reading:

Domain Driven Design by Eric Evans

Throwing exceptions the right way

Use ReSharper? Notice every time ReSharper sees code like this:

catch (Exception ex)
{
    // some exception handling, or logging here
    throw ex;
}

it complains, and tells you to get rid of the ex for the reason ‘Exception rethrow possibly intended’?

The reason ReSharper is warning you about an ‘exception rethrow’ is that when you rethrow an exception it replaces the stack trace of the original exception with the current location. So if you print the stack trace further up the code you will not be able to see the statement which caused the exception in the first place!

For this reason, you should ALWAYS use this instead:

catch (Exception ex)
{
    // exception handling
    throw;
}

Handling multiple exceptions

Further on exception handling, if your code might throw multiple types of exceptions and you want to handle the exceptions differently then you can build up a hierarchy of catch clauses from the most specific (SqlException e.g.) at the top, to the least specific (Exception) at the bottom like this:

try
{
    // do something that can might throw an exception
}
catch (SqlException sqlEx)
{
    // retry on timeout or deadlock for example?
}
catch (Exception ex)
{
    // handle more generic exception
}
finally
{
    // put any clean up operations here
}

It’s worth noting that, if you are catching the more general exceptions further up the chain your exception handling code for more specific types of exception lower down the list will never be called! But fortunately tools like ReSharper will warn you first :-)

Another thing you might want to consider is to wrap the built-in exception types into a custom Exception type and maybe use an enum to categorise the different exceptions into well defined types that your application understands (e.g. ServerError, FeedError, DatabaseError, etc.).

In the case of WCF services, you can also specify fault contracts for each operation and in your catch clauses on the server side wrap all exceptions into faults so when exceptions happen they don’t fault your channel. For more on WCF error handling and fault conversion, have a look at this article.

Controlling Type conversion in C#

Ever run into a situation where your application needs to use a type for its internal working but occasionally need to convert that type into another just so it can be passed to another application which doesn’t understand some of the base types we have in the .Net space?

Consider the example below, where the Player is a type in my problem domain, but I need to communicate information about the player with a non-.Net client which doesn’t have the Guid type, so I need to have a PlayerDTO type used exclusively for message passing:

public sealed class Player
{
    public Player(string name, long score)
    {
        Name = name;
        Score = score;
        ID = Guid.NewGuid();
    }

    public string Name { get; private set; }
    public Guid ID { get; private set; }
    public long Score { get; private set; }
}

public sealed class PlayerDTO
{
    public PlayerDTO(string name, long score, string id)
    {
        Name = name;
        Score = score;
        ID = id;
    }

    public string Name { get; private set; }
    public string ID { get; private set; } // client is not .Net based so no Guid there
    public long Score { get; private set; }
}

The problem here is that there is no easy way to convert the Player type to PlayerDTO and every time I want to create a new PlayerDTO object I need to manually copy the values from Player into PlayerDTO’s constructor, and my application needs to know that it needs to convert Player.PlayerID into a string.

A cleaner solution here is to overload either the implicit or explicit converter so you can simply cast a Player object into a PlayerDTO object:

// Overload explicit cast converter to allow easy conversion from a Winner to WinnerAmfvo object
public static explicit operator PlayerDTO(Player player)
{
    return new PlayerDTO(player.Name, player.Score, player.PlayerID.ToString());
}

Further more, this allows you to easily convert an array of Player objects into an array of PlayerDTO objects:

// use Array.ConvertAll
PlayerDTO[] playerDTOs = Array.ConvertAll(players, p => (PlayerDTO) p);
// use Linq
playerDTOs = players.Select(p => (PlayerDTO) p).ToArray();

No Interface types allowed

One thing to bear in mind when using the implicit/explicit operators is that you won’t be able to use interface types, and the reason is specified in Section 10.9.3 of the C# spec.

In short, defining an implicit or explicit conversion between reference types gives the user the expectation that there will be a change in reference; after all, the same reference cannot be both types. On the other hand, the user does not have the same expectation for conversions between reference types and interface types.

In these cases, you still have other ways to make type conversion cleaner and centralised, for example:

Create a FromIPlayer method


playerDTOs = iPlayers.Select(p => PlayerDTO.FromPlayer(p)).ToArray();

Put all conversions in a PlayerConvert static object

If you have lots of types which can be converted to many types then it might be a cleaner solution to just put all the conversions into one static object, like the System.Convert class. You then use it like this:


playerDTOs = iPlayers.Select(p => PlayerConvert.ToPlayerDTO(p)).ToArray();

References:

StackOverflow question on why you can't use interface types with implicit/explicit operator

Feb 11th – Scott Guthrie Talks Shop IV

This is an upcoming web seminar with Scott Gu, organised by the good folks at Linked .Net User Group (http://www.lidnug.org).

I attended one of their previous presentations with Joe Albahari on the new features in C# 4.0 (the recorded presentation can be viewed here) and thoroughly enjoyed that! A FREE web seminar with someone as influential in the .Net space as Scott Gu’s gotta be good!

Who those of you who doesn’t know who Scott Gu is, he’s a VP and one of the founding members of the Microsoft’s .Net platform and runs the development teams responsible for Visual Studio developer tools and technologies for building web applications (e.g. ASP.NET MVC).

(Unconfirmed story!) Whilst still an intern, he developed the original ASP.NET platform with another senior developer at Microsoft, just to give you some idea about who the man is :-)

The link to the event is:

https://www.livemeeting.com/cc/microsoft/join?id=G2K4BH&role=attend&pw=PN6.%3CQ%5Drb

and to find out what time it starts in your time zone, go here:

http://www.timeanddate.com/worldclock/fixedtime.html?month=2&day=11&year=2010&hour=10&min=0&sec=0&p1=256

In the meantime, check out Scott Gu’s excellent blog!