DEV Community

Kiron Roy
Kiron Roy

Posted on • Updated on

Extension Methods with Cats

Extension methods improves code readability. There are three requirements for Extension methods:

  • Extension methods must be static.
  • Extension methods need to be in a static Class.
  • Extension uses the this syntax.
Instantiated Class (1)
CatModel public
CatName property of string type
CatType property of string type
CatAge property of int type
Static Class (1)
ConsoleCatStuff public static
RequestAString RequestAString(this string message)
RequestAInt RequestAnInt(this string message, int minValue, int maxValue)
... ... ...
Program.cs

In the program file, cat (object) is created from the CatModel (class "blue print (or CAD drawing)". The properties:

  • CatName
  • CatType
  • CatAge

are declared and used by their respective extension methods:

  • RequestAString()
  • RequestAnInt()

They can be easier to read because the data, in the case of cat.CatsName comes first followed by the method name. Moreover, a developer can "chain" methods:

 person.CatsName = "what is your cat's name: ".ToLower().RequestString();

//Would produce this output:
 "what is your cat's name"
Enter fullscreen mode Exit fullscreen mode

Note, order matters. The C# built-in method ToLower() must be called before the user's RequestAString() method.

using System;

namespace ExtensionMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            CatModel cat = new CatModel();

            Console.WriteLine(); // breakline

            cat.CatsName = "What is your cat's name: ".ToLower().RequestAString();

            cat.CatType = "What type cat is it: ".RequestAString();

            cat.CatAge = "What is your cat's age: ".RequestAnInt(1, 112);

            cat.CatInfoPrint();

            Console.ReadLine();
        }
    }
}

Enter fullscreen mode Exit fullscreen mode
CatModel.cs

using System;

namespace ExtensionMethods
{
    public class CatModel
    {
        public string CatsName { get; set; }
        public string CatType { get; set; }
        public int CatAge { get; set; }


        public void CatInfoPrint()
        {
          Console.WriteLine();
            Console.WriteLine("--------------------------------------------------------");
            Console.WriteLine();
            Console.WriteLine($"Your cat's name is {CatsName}. " +
                $"It is a {CatType}, and the cat's age is {CatAge} years old");
            Console.WriteLine();
            Console.WriteLine("--------------------------------------------------------");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
ConsoleStuff.cs

The ConsoleStuff class uses the System.Globalization to provide proper captialization from a user's input. So if a user typed nIcK for the cat's name. It would store and print out Nick. The Trim() method would cut out extra spaces.

using System;
using System.Globalization;

namespace ExtensionMethods
{
    // Extenstion methods they make code easier to write and read
    public static class ConsoleHelper
    {
        public static string RequestAString(this string message)
        {
            string output = "";
            string outputCaps = "";

            while (string.IsNullOrWhiteSpace(output))
            {

                Console.Write(message);
                output = Console.ReadLine().Trim();
                outputCaps = new CultureInfo("en-US").TextInfo.ToTitleCase(output);
            }

            return outputCaps;
        }

        public static int RequestAnInt(this string message, int minValue, int maxValue)
        {
            return message.RequestAnInt(true, minValue, maxValue);
        }

        public static int RequestAnInt(this string message)
        {
            return message.RequestAnInt(false);
        }

        private static int RequestAnInt(this string message, bool useMinMax, int minValue = 0, int maxValue = 0)
        {
            int output = 0;
            bool isValidInt = false;
            bool isInValidRange = true;

            while (isValidInt == false || isInValidRange == false)
            {
                Console.Write(message);
                isValidInt = int.TryParse(Console.ReadLine(), out output);

                    if (output >= minValue && output <= maxValue)
                    {
                        isInValidRange = true;
                    }
                    else
                    {
                        isInValidRange = false;
                   }
                }
            }

            return output;
        }
    }
}

Enter fullscreen mode Exit fullscreen mode
Output
what is your cat's name: nick
What type cat is it: maine coon
What is your cat's age: 12

--------------------------------------------------------

Your cat's name is Nick. It is a Maine Coon, and the cat's age is 12 years old.

--------------------------------------------------------
Enter fullscreen mode Exit fullscreen mode
Code below on Repl.it

Discussion (0)