tags:

views:

110

answers:

4

something like

public static class StringHelpers
{
    public static char first(this string p1)
    {
        return p1[0];
    }

    public static implicit operator Int32(this string s) //this doesn't work
    {
        return Int32.Parse(s);
    }
}

so :

string str = "123";
char oneLetter = str.first(); //oneLetter = '1'

int answer = str; // Cannot implicitly convert ...
+2  A: 

Unfortunately C# does not allow you to add operators to any types that you don't own. Your extension method is about as close as you are going to get.

Andrew Hare
+3  A: 

No, there's no such thing as extension operators (or properties etc) - only extension methods.

The C# team have considered it - there are various interesting things one could do (imagine extension constructors) - but it's not in C# 3.0 or 4.0. See Eric Lippert's blog for more information (as always).

Jon Skeet
Didn't they plan to add extension properties to c# 4.0? Why was it left out?
Tamás Szelei
@sztomi: I don't know of it ever being "planned" - it was "discussed" but that's not the same thing. Of course it *might* have been planned - I'm not party to the C# team's internal planning meetings :)
Jon Skeet
A: 

What you are trying to do in your example (defining an implicit operation from string to int) is not allowed.

Since an operation (implicit OR explicit) can only be defined in the class definition of the target or destination class, you cannot define your own operations between framework types.

Greg
Even if it was allowed, an implicit conversion from string to int would be something out of a nightmare. Implicit conversions are typically only done when converting to types don't involve any loss of information (ex: int -> long).
Greg
A: 

I am thinking your best bet is something like this:

public static Int32 ToInt32(this string value)
{
    return Int32.Parse(value);
}
ChaosPandion