Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I extend int.TryParse method?

Tags:

c#

parsing

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

like image 586
Delashmate Avatar asked Dec 03 '22 07:12

Delashmate


1 Answers

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)
   {
     ...
   }
}
like image 156
Jamiec Avatar answered Dec 15 '22 10:12

Jamiec