Home > Mobile >  Visual studio C# VSTO: Refactoring
Visual studio C# VSTO: Refactoring

Time:05-19

Coming from Visual basic, I kind of miss the With statement that is lacking in C#, I'm looking for ways to refactor the code so it's not so crowded.

I have the following code:

Globals.Ribbons.RibbonMain.chkCalculation.Checked = (Globals.ThisAddIn.Application.Calculation == Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationAutomatic);
Globals.Ribbons.RibbonMain.chkScreenUpdating.Checked = Globals.ThisAddIn.Application.ScreenUpdating;
Globals.Ribbons.RibbonMain.chkEvents.Checked = Globals.ThisAddIn.Application.EnableEvents;
Globals.Ribbons.RibbonMain.chkDisplayAlerts.Checked = Globals.ThisAddIn.Application.DisplayAlerts;

How can I extract the common denominators to trim down the code to make it more legible?

What I thought is creating the 2 variables below, but i don't know the variable type I should use. Is there somewhere I could look for the variable type?

variableType R = Globals.Ribbons.RibbonMain
variableType A = Globals.ThisAddIn.Application

CodePudding user response:

var should work fine, let the compiler figure out the type:

    var R = Globals.Ribbons.RibbonMain;
    var A = Globals.ThisAddIn.Application;
    
    R.chkCalculation.Checked = (A.Calculation == Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationAutomatic);
    R.chkScreenUpdating.Checked = A.ScreenUpdating;
    R.chkEvents.Checked = A.EnableEvents;
    R.chkDisplayAlerts.Checked = A.DisplayAlerts;

CodePudding user response:

Thank you @madreflection for sharing the knowledge.

As I'm using the 2 variables in multiple places, I extracted them as Static variables.

using EXCEL = Microsoft.Office.Interop.Excel;

    internal class clsMacros
    {
        //GLOBAL VARIABLES
        static RibbonMain RIBBON = Globals.Ribbons.RibbonMain;
        static EXCEL.Application APPLICATION = Globals.ThisAddIn.Application;

        public static void GetStatus()
        {
            RIBBON.chkCalculation.Checked = (APPLICATION.Calculation == EXCEL.XlCalculation.xlCalculationAutomatic);
            RIBBON.chkScreenUpdating.Checked = APPLICATION.ScreenUpdating;
            RIBBON.chkEvents.Checked = APPLICATION.EnableEvents;
            RIBBON.chkDisplayAlerts.Checked = APPLICATION.DisplayAlerts;        
        }
    }
  • Related