1

Tuples rock my world too

by klh 10. april 2008 14:33

Just read the blogpost Tuples rock my world, and liked it.

After looking at it I thought "you can do this in C# as well".

Please note I understand that tuples are part of F# which is a major difference to C#.

But I too have been disturbed many times by the having to have two lines of code in order to parse a string or the likes.

This is the code I ended up with, which is pretty close to the F# in the post....

 

string test = "1234";
TryParseTuple<int> kln = TryParseWrapper<int>.TryParse(Int32.TryParse, test);

 

Using Visual Studio 2008 i get anonymous types and get even simpler code:

var kln = TryParseWrapper<int>.TryParse(Int32.TryParse, test);

 

If you want to look at the code implementing this stuff, here goes:

 

Well first we need to make a tuple to return.

I reckon the TryParse pattern is only used on value types - maybe I am wrong?

public class TryParseTuple<T> where T : struct
    {
        public readonly T _theParsedValue;
        public readonly bool _parsed;
        public TryParseTuple(bool parsed, T theParsedValue)
        {
            this._theParsedValue = theParsedValue;
            this._parsed = parsed;
        }
    }
 

In order to parse I choose to pass a delegate to the TryParse method,

one could probably do some reflection stuff in order to eliminate passing this delegate.

But since i wrote this in 10 minutes I went for the fast lane....

 
public delegate bool TryParseDelegate<T>(string input, out T output) where T : struct;
    
 So lastly here is the class that wraps the TryParse delegate and returns a TryParseTuple   
    public class TryParseWrapper<T> where T : struct
    {
        public static TryParseTuple<T> TryParse(TryParseDelegate<T> theDelegate, string input)
        {
            T t;
            bool parsed = theDelegate(input, out t);
            return new TryParseTuple<T>(parsed, t);
        }
    }

Tags:

Kommentarer

Tilføj kommentar


(Viser dit Gravatar icon)  

  Country flag

biuquote
  • Kommentar
  • Eksempel
Loading



Powered by BlogEngine.NET 1.4.5.0
Original Design by Laptop Geek, Adapted by onesoft