Create methods like .ToString ()

I want to create my own methods, such as .ToString() , which I want to use in my own project.

For example ToDecimalOrZero() , which I want to convert data to decimal, or if the data is empty, convert them to zero.

I know that I should not ask for codes here, but I have no idea how I can do this.

Can anyone help me out? Or at least call me somewhere ... I'm a little lost. Thanks:)

+4
source share
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 
+9
source

Here is an example of how to write custom 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 must be static , as well as a class containing extension methods

+10
source

Source: https://habr.com/ru/post/1484360/


All Articles