Etrit
Etrit

Reputation: 885

Create methods like .ToString()

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

Upvotes: 4

Views: 4474

Answers (2)

Ahmed KRAIEM
Ahmed KRAIEM

Reputation: 10427

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

Upvotes: 11

Michael Schnerring
Michael Schnerring

Reputation: 3661

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

Upvotes: 11

Related Questions