C# Extension method | Extending methods of existing classes

Program


using System;

namespace SampleConsoleAppln
{
    public static class IntExtensions
    {
        public static bool IsInvalid(this int mark, int MaxMark)
        {
            return (mark < 0 || mark > MaxMark); //true or false
        }
    }

    //Extension-method must be defined in a top-level of static class;
    //The class containing Extension methods should not be nested inside      //the another class. Here the following class is a static class.

    class ExtensionMethodExample
    {
        public static void Main(String[] x)
        {
            Console.WriteLine("Enter the max mark");
            int MaxMark = int.Parse(Console.ReadLine());

            GetMark:
            Console.WriteLine("Enter scored mark");
            int ScoredMark = int.Parse(Console.ReadLine());

            bool result = ScoredMark.IsInvalid(MaxMark);
            if (result)
            {
                Console.WriteLine("Invalid mark entered");
                goto GetMark;
            }

            Console.WriteLine("You have scored : {0}", ScoredMark);
            Console.ReadKey();
        }
    }
}


Output

Enter the max mark
100

Enter scored mark
101
Invalid mark entered

Enter scored mark
-10
Invalid mark entered

Enter scored mark
95

You have scored: 95

No comments:

Post a Comment