Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In c# 3.0, is it possible to add implicit operators to the string class?

Tags:

c#

implicit

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 ...
like image 716
Enriquev Avatar asked Nov 24 '09 18:11

Enriquev


2 Answers

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).

like image 128
Jon Skeet Avatar answered Sep 21 '22 14:09

Jon Skeet


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.

like image 35
Andrew Hare Avatar answered Sep 21 '22 14:09

Andrew Hare