Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create methods like .ToString()

Tags:

c#

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 :)

like image 406
Etrit Avatar asked Nov 29 '22 12:11

Etrit


2 Answers

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
like image 193
Ahmed KRAIEM Avatar answered Dec 05 '22 01:12

Ahmed KRAIEM


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

like image 42
Michael Schnerring Avatar answered Dec 05 '22 02:12

Michael Schnerring