4

I wish I had the following method

int num;  
int.TryParse("5",out num, 10);

Which will do the same as TryParse, but addtional if the parsing fails, the out parameter will get the defualt value 10

Can I implement it?

With extension methods I can implement the following:

int num;
num.TryParse("5",out num, 10);

But this look different than the rest of the TryParse methods..

Delashmate
  • 2,344
  • 5
  • 26
  • 40
  • 1
    Checkout this link http://stackoverflow.com/questions/1078512/why-does-integer-tryparse-set-result-to-zero-on-failure – Tim B James Sep 21 '11 at 11:08

7 Answers7

6

You cannot add static methods to existing classes, but you can add your own static method to your own class, for example:

public static class MyConversions
{
   public static bool TryParse(string value, out int num, int defaultValue)
   {
     ...
   }
}
Jamiec
  • 133,658
  • 13
  • 134
  • 193
4

A one-liner without writing a helper method would be:

int num = int.TryParse("5", out num) ? num : 10;


And here is a string-extension method: http://neue.cc/2010/04/09_251.html

ulrichb
  • 19,610
  • 8
  • 73
  • 87
2

You could create an extension method for string:

int num;
"5".TryParse(out num, 10);
Henrik
  • 23,186
  • 6
  • 42
  • 92
2

There is no way to implement static extension method. Look at this question: Static extension methods
Ways to go:
a. Implement extension method on strings not ints:

public static int Parse(this string s, int defaultValue) {
   int result;
   return Int32.TryParse(s,out result) ? result : defaultValue;
}
...
int num = "5".Parse(10); //

b. Implement your own IntUtil class with TryParse(string, out int, int) method.

Community
  • 1
  • 1
default locale
  • 13,035
  • 13
  • 56
  • 62
1

You can't create static extension methods, so you can't do what you want unfortunately.

If you really didn't like what you've got so far (non-static method) then you could create your own class with that static method as per @Jamiec's answer.

George Duckett
  • 31,770
  • 9
  • 95
  • 162
1

TryParse returns an boolean to say if the parsing worked or not. So:

int num;
if (!num.TryParse("5", out num))
{
    num = 10;
}

You can't use that as an extension method, but you can still leave it somewhere appropriate as a static method.

MPelletier
  • 16,256
  • 15
  • 86
  • 137
1

You can't extend TryParse. Both because it is a static method and because Int32 is a struct can can't be inherited from.

You can write your own extension method though.

Oded
  • 489,969
  • 99
  • 883
  • 1,009