<TeRanEX/> weblog v2

Archive for March, 2009

Implicit conversions in C#

Yesterday I came across an interesting article: What’s the opposite of Nullable. While the solution for Non-Nullability is interesting, the reason i’m blogging this is because the article also used a C# feature which i didn’t know of: implicit conversions.

And guess what? Today I had a situation where I could use these implicit conversions. My app reads data from a CSV-file, so all the input are just strings. Until now that was just fine. However, at one part of my code I had to process one of the fields which has a fixed format. Say a field is a phonenumber and i need the country-prefix. So I created a PhoneNumber-class like this:

?View Code CSHARP
public class PhoneNumber
{
  private readonly string _number;
 
  public PhoneNumber(string number)
  {
      if (!new Regex(PHONE_NUMBER_REGEX).IsMatch(number))
      {
          throw new ArgumentException("Invalid phone number", "number");
      }
      _number = number;
  }
 
  public string Prefix
  {
    get { return GetPrefixFromNumber(...); }
  }
}

Now it is possible to create a (helper-)method in another class to get the prefix like this (this is just a simple example):

?View Code CSHARP
public string GetPrefix(PhoneNumber phoneNumber)
{
  return phoneNumber.Prefix;
}

But when you only have the phonenumber as a string, you’ll still have to create an instance of PhoneNumber to be able to call the GetPrefix method:

?View Code CSHARP
var prefix = GetPrefix(new PhoneNumber("+32485123456"));

That is, until we add a method for implicit conversion to the PhoneNumber-class:

?View Code CSHARP
public class PhoneNumber
{
  private string _number;
 
  public PhoneNumber(string number)
  {
      if (!new Regex(PHONE_NUMBER_REGEX).IsMatch(number)
      {
          throw new ArgumentException("Invalid phone number", "number");
      }
      _number = number;
  }
 
  public string Prefix
  {
    get { return GetPrefixFromNumber(...); }
  }
 
  public static implicit operator PhoneNumber(string number)
  {
    return new PhoneNumber(number);
  }
}

Now it is possible to call the GetPrefix method with just a string. The string will be automagically converted to a PhoneNumber, unless it is invalid, in which case the ArgumentException will be thrown:

?View Code CSHARP
var prefix = GetPrefix("+32485123456");

Wednesday, March 25th, 2009 - Posted in Programmeren - Comments Off

Techdays

Gisteren mocht ik voor het werk een dagje van de Microsoft Techdays bijwonen. Het was de eerste keer dat ik naar een Microsoft-event ging en had me eerlijk gezegd aan veel show en weinig inhoud verwacht. In sterk contrast tot JavaPolis Devoxx, waar er veel inhoud en weinig show is. Achteraf bekeken viel dit eigenlijk enorm goed mee. Enkel de keynote ging er wat over. Een Developer Evangelist of Regional Director moet echt niet als één of andere superster worden aangekondigd met loeiharde muziek en lichtshow, maar dat is mijn mening natuurlijk.

Na de keynote heb ik de sessie over C# 4.0 gevolgd en dat was erg interessant. C# 4.0 belooft weer een versie te worden om naar uit te kijken. Eén van de nieuwe features is het dynamic keyword. Dit zorgt ervoor dat je methodes op het object kan oproepen waarbij de compiler niet checked of deze effectief bestaan. De check wordt pas ‘at runtime’ gedaan. Dit is erg handig om te integreren met andere talen zoals Javascript en Ruby.

Een andere interessante feature is ‘Generic co- and contra- variance’. Hiermee kan je in speciale gevallen casts uitvoeren zoals:

?View Code CSHARP
var list = new List<string>();
(List<object>)list;
</object></string>

Ook optional en named parameters behoren tot de nieuwe features. Dit is ook erg interessant. Bekijk dit voorbeeldje:

?View Code CSHARP
public void Order(string name, int amount = 2, int discount = 0)
{ ... }
 
Order("jeroen", dicount: 5);
// the first param - name - is not optional so a value must be supplied.
// the second param - amount - has default value of 2 which we want to use
// the third param - discount - has a default value of 0 but we supply 5

Enkele belangrijke punten bij het gebruikt van deze feature zijn wel dat je parameters absoluut als constante moet beschouwen. Je kan na verloop van tijd in veel gevallen immers niet zomaar de standaard waarde van een parameter aanpassen. Als je in voorgaand voorbeeld de default value van amount zou wijzigen in 3 zouden er plots veel klanten 3 items bestellen in plaats van 2. Ook is het wijzigen van de naam van een parameter niet meer zo vanzelfsprekend omdat deze naam nu ook buiten de methode wordt gebruikt.

Read the rest of this entry »

Thursday, March 12th, 2009 - Posted in Programmeren - 2 Comments

Activity Stream

You are currently browsing the weblog archives for March, 2009.

Categories

Advertisement

eMusic.com
Download 25 FREE songs at eMusic.com!

Latest Comments

Jonas: Grats. Klinkt als een leuke job. En zo dicht bij huis dat wil ik ook wel ;)

teranex: @Vincent: Gek genoeg heeft microsoft voor de volgende versie van Visual Studio...

Vincent Ceulemans: Tsja, consequent zijn is voor MS waarschijnlijk wat te moeilijk,...

teranex: @krzychu yes it works without the Nucleus files and database, because it uses...

krzychu: Your tips about importing/migration from Nuclues to WP works very well. Thank...

Archives

2010 2009 2008 2007 2006 2005 2004 2003

Links

Info

This blog is powered by WordPress and is hosted by Dreamhost

Get Mozilla Firefox and rediscover the web.