Search code examples
c#cakebuild

Sharing global variables across .cake files


I use CAKE 0.21.1.0.

My build.cake script loads another .cake script: tests.cake.

I have defined some global variables in build.cake that I would like to use in both my .cake scripts.

Let's say I have a global variable named testDllPath.

When I use testDllPath in tests.cake, I see the following error:

error CS0120: An object reference is required for the non-static field, method, or property 'testDllPath'

If I try to declare a new variable also named testDllPath in tests.cake, I see this error instead:

error CS0102: The type 'Submission#0' already contains a definition for 'testDllPath'

How should I get access to the global variables defined in build.cake from another .cake file?


Solution

  • Yes if you load it after you declared it.

    I.e. this won't work

    #load "test.cake"
    FilePath testDLLPath = File("./test.dll");
    

    this will work

    FilePath testDLLPath = File("./test.dll");
    #load "test.cake"
    

    A more elegant way is probably to have file with common variables and load that first i.e.

    #load "parameters.cake"
    #load "test.cake"
    

    If you're trying to access a local variable from a static method or a class this won't work because of scoping.

    In those scenarios you've got a few options

    1. Pass variables to methods
    2. Pass variables class constructors
    3. Use public static properties/fields which will be accessible from anywhere.

    The advantage of static/parameter usage us that load order won't matter.

    Example local variable static method

    File testDLLPath = File("./test.dll");
    
    RunTests(testDLLPath);
    
    public static void RunTests(FilePath path)
    {
        // do stuff with parameter path
    }
    

    Example pass variable to constructor

    File testDLLPath = File("./test.dll");
    
    var tester = new Tester(testDLLPath);
    
    tester.RunTests();
    
    
    public class Tester
    {
       public FilePath TestDLLPath { get; set; }       
    
       public void RunTests()
       {
           //Do Stuff accessing class property TestDLLPath
       }
    
       public Tester(FilePath path)
       {
            TestDLLPath = path;
       }
    }
    

    Example static properties

    BuildParams.TestDLLPath  = File("./test.dll");
    
    RunTests();
    
    
    public static void RunTests()
    {
        // do stuff with BuildParams.TestDLLPath
    }
    
    public static class BuildParams
    {
       public static FilePath TestDLLPath { get; set; }    
    }