Extension methods in C#


An extension method is simplified the implementation and Reduce the calling syntax.

For Example several scenarios we need to display decimal format as fixed two. Every time we are writing separate logic for this. Using an extension method we can solve this issue.
Note:it will support .Net 3.5 or above

public static class ExtentionMethods

    {
        public static string SetPrecision(this decimal value)
        {
            return value.ToString("C2");
        }
    }

The above implementation is called Extension implementation. Once implement this it will accessible anywhere within the reference.

    public class test
    {
        decimal _decimal;
        test()
        {

          var s=  _decimal.SetPrecision();

        }
    }

No comments:

Post a Comment