Skip to main content

Promote to Generic Parameter

  • 3 minutes to read

Purpose

Takes a class reference or struct reference inside a method block and turns that into a type parameter of the generic method. The Promote to Generic Parameter refactoring also updates all calling code.

This refactoring reduces the time it takes to make a method applicable to more classes in your code.

Availability

Available when the cursor is in a class reference or struct reference in a method.

How to Use

  1. Place the caret in a class reference or struct reference in a method.

    using System;
    
    namespace ConsoleApp15
    {
        public class Verifier
        {
            public string CheckText(string text)
            {
                var validatedText = text ?? "";
                if (TrimSpaces)
                    validatedText = validatedText.Trim();
                return validatedText;
            }
            public bool TrimSpaces { get; set; }
        }
    
        interface SpellChecker
        {
            string Check(Verifier verifier, string text);
        }
    
        class Control : SpellChecker
        {
            void SetRules<V>(V verifier)
                where V : Verifier
            {
                verifier.TrimSpaces = true;
            }
            public string Check(Verifier verifier, string text)
            {
                SetRules<Verifier>(verifier);
                return verifier.CheckText(text);
            }
            public void LogText(string text)
            {
                string verifiedText = Check(new Verifier(), text);
                Console.WriteLine(verifiedText);
            }
        }
    }
    
  2. Press Ctrl+. or Ctrl+~ to invoke the Code Actions Menu.

  3. Select Promote to Generic Parameter from the menu and press Enter.

    promote

After execution, this refactoring turns a regular method into a generic method.

using System;

namespace ConsoleApp15
{
    public class Verifier
    {
        public string CheckText(string text)
        {
            var validatedText = text ?? "";
            if (TrimSpaces)
                validatedText = validatedText.Trim();
            return validatedText;
        }
        public bool TrimSpaces { get; set; }
    }

    interface SpellChecker
    {
        string Check<T>(T verifier, string text) where T : Verifier;
    }

    class Control : SpellChecker
    {
        void SetRules<V>(V verifier)
            where V : Verifier
        {
            verifier.TrimSpaces = true;
        }
        public string Check<T>(T verifier, string text) where T : Verifier
        {
            SetRules<T>(verifier);
            return verifier.CheckText(text);
        }
        public void LogText(string text)
        {
            string verifiedText = Check<Verifier>(new Verifier(), text);
            Console.WriteLine(verifiedText);
        }
    }
}