Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method for Int32 in C#

I envisage the ability to write fluent code that adds meaning to numbers within codebases. Say you wanted a number to represent a distance in miles. You'd have something like:

Usage:

var result = myMethod(100.Miles());

I think this would be much more readable than simply passing in the int, plus you could presumably apply bounds checking to the Miles type.

Extension method and struct implementation:

static class IntExtensions
{
  public static Miles(this int i) { get { return new Miles { Count = i }; } }
}

public struct Miles
{ 
  public int Count { get; private set; } //optionally perform bounds checking
} 

Would such an idea be useful, or is it too late on a hot Friday?

Edit: Yes, doesn't look quite so neat without extension properties... Apologies for the rushed invalid code. It was just an idea.

like image 479
Ben Aston Avatar asked Jun 25 '10 15:06

Ben Aston


1 Answers

It's an interesting idea, but I would ask for a really strong use case before doing something like this. For one thing, once a number is cast as a "mile", you can no longer treat it as an int. You either have to implement the whole gamut of operators, or cast the miles back to integers before performing arithmetic on them. It's a lot of extra work if there's no good reason to do it.

There are some cases where this would be a good strategy, though. I think I remember hearing about a multi-million-dollar rocket or something that failed NASA once lost a $125 million space ship because programmers were passing the wrong units of measure into a function. This would help you to avoid that problem.

On a related note, you might be interested in F#, which has built-in support for units of measure.

like image 183
StriplingWarrior Avatar answered Sep 23 '22 02:09

StriplingWarrior