Search code examples
c#visual-studiorefactoringvsto

Visual studio C# VSTO: Refactoring


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

Solution

  • 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;        
            }
        }