I want to create my own methods like .ToString()
which I want to use on my own project.
For example ToDecimalOrZero()
which I want to convert the data into decimal, or if the data is empty convert it to zero.
I know I shouldn't ask for codes here, but I don't have the slightest idea how I can do that.
Can anyone help me out? Or at least refer me somewhere... I'm kinda lost. Thanks :)
Use extension methods:
namespace ExtensionMethods
{
public static class StringExtensions
{
public static decimal ToDecimalOrZero(this String str)
{
decimal dec = 0;
Decimal.TryParse(str, out dec);
return dec;
}
}
}
using ExtensionMethods;
//...
decimal dec = "154".ToDecimalOrZero(); //dec == 154
decimal dec = "foobar".ToDecimalOrZero(); //dec == 0
Here an example of how to write your own extension methods
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
from MSDN
Note that extension methods have to be static, as well as the class that contains extension methods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With