0

Possible Duplicate:
Static extension methods

So I know that Extension methods are for object instances only as in doing

public static string stringBig(this string inString) {
     return inString.ToUpper();
}

Only works for an instance of string

However I am trying to make something that function like Double.TryParse so that I don't have to do

Double myDouble = someOtherDouble.DoubleParseDifferent("4.324802348203498");

I'd like to be able to do something like

Double myDouble = Double.DoubleParseDifferent(someRandomString);

Now I know that I can't actually do this so what would be some alternative methods or ways I could approach this.

Community
  • 1
  • 1
msarchet
  • 15,104
  • 2
  • 43
  • 66

3 Answers3

3

You can make a class with a similar name:

static class MyDouble { ... }
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

The only possible alternative way for implementing TryParse I can think of (since what you're asking for is not possible) would be creating a normal static method, but returning a nullable.

public static double? TryParseEx(string value) { /* new improved parse code here */ }

var result = TryParseEx("1234.56");

That way you would not need a output parameter like the normal TryParse...

If !result.HasValue, then the parse was not successful. Otherwise, just read the result.Value property to get the parsed result.

rsenna
  • 11,775
  • 1
  • 54
  • 60
  • hmmm this may be the style of thought I may go for doing this. I know what I was asking for wasn't possible which is why I wanted some other way. – msarchet Jan 05 '11 at 21:04
1

Since you're adding a string parsing method, why not add an extension to string

public static Double ParseDifferent( this string inString) {
     return ...
}
Paul Alexander
  • 31,970
  • 14
  • 96
  • 151