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

1

7 Answers 7

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)
   {
     ...
   }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

You could create an extension method for string:

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

Comments

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.

Comments

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.

Comments

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.