Skip navigation

teranex weblog

top menu

.net

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:

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
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):

1
2
3
4
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:

1
var prefix = GetPrefix(new PhoneNumber("+32485123456"));

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

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
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:

1
var prefix = GetPrefix("+32485123456");

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:

1
2
var list = new List<string>();
(List<object>)list;

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

1
2
3
4
56
7
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.

ASP.NET MVC 1.0 Quickly

Today I was pretty surprised when going through my feeds to read that a friend of mine, Maarten Balliauw, has a written a book. The title of the book is ASP.NET MVC 1.0 Quickly:

It’s been quite a job, but there it is: Packt just announced my very first book on their site. It is titled “ASP.NET MVC 1.0 Quickly”, covering all aspects ASP.NET MVC offers in a to-the-point manner with hands-on examples. The book walks through the main concepts of the MVC framework to help existing ASP.NET developers to move on to a higher level. It includes clear instructions and lots of code examples. It takes a simple approach, thereby allowing you to work with all facets of web application development. Some keywords: Model-view-controller, ASP.NET MVC architecture and components, unit testing, mocking, AJAX using MS Ajax and jQuery, reference application and resources.

I always thought, and still think, that writing a book is a massive amount of work. Therefore i really have a lot of respect for people that have the courage to actually write a real book.

In his blogpost Maarten explains why and how he wrote the book. According to his time tracking software, it took him 100 hours to write the book, which is far less than i would expect. On the other side, if you can only use spare time to do the work, it is a lot of time. Maarten also explains that he used Subversion to keep his work versioned and that some people laughed at him for doing so. I don't think this is such a strange idea. If I ever would write a book (consider the chances small...), I certainly would use Subversion, or a similar tool, to store my work. In fact, when my girlfriend wrote her paper for her last schoolyear I also made her use Subversion to store her word-documents. But i do find it strange that you write a complete book in Word (which is a word processor btw, not a text editor ;) ).

I'm very curious to see and read the book. Btw Maarten, is that your own pair of glasses on the cover? Anyway, Congrats Maarten!

Mono 2.0 Packages for Ubuntu Intrepid | eric's extremeboredom

I was disappointed to read that Intrepid will not include Mono 2.0, so I created packages. They’re available for download from my PPA.

http://eric.extremeboredom.net/2008/10/15/296

Remove the .NET Framework Assistant 1.0 from Firefox « adrift

The newest (3.5 SP1) .NET installs an extension (Microsoft .NET Framework Assistant 1.0) for Firefox (you guessed right: without asking) and even alters the user agent. To maximize “user friendliness”, the uninstall button is inactive. However, regedit helps.

http://nambulous.wordpress.com/2008/08/23/remove-the-net-framework-assistant-10-from-firefox/

Hacking Visual Studio to Use More Than 2Gigabytes of Memory

Article on how to enable VS2008 to use more then 2Gig of memory. Could be useful one day

http://stevenharman.net/blog/archive/2008/04/29/hacking-visual-studio-to-use-more-than-2gigabytes-of-memory.aspx

String.Format("{0}", "formatting string"};

Quick reference for the C# String.Format method

http://idunno.org/archive/2004/14/01/122.aspx

Ninject: Lightning-fast dependency injection for .NET

Ninject is an ultra-lightweight, ultra-fast dependency injection framework for .NET 2.0 applications. Easy to use, fast, flexible, and powerful, Ninject aims to make inversion of control accessible to all types of .NET projects, regardless of size or comp

http://ninject.org/

Rhino Mocks - Ayende @ Wiki

A dynamic mock object framework for the .Net platform. It's purpose is to ease testing by allowing the developer to create mock implementations of custom objects and verify the interactions using unit testing.

http://www.ayende.com/Wiki/(S(eox1ipfwjzugrm55yiu54wfe))/Default.aspx?Page=Rhino+Mocks