Search code examples
c#visual-studio-2015uwpwindows-10-mobile

Share variables between projects in the same solution


I have a solution and two projects in it. I want to share variables from project1 to project2 and viceversa. How can i do that? Maybe with a static class but I don't know how can handle it.


Solution

  • If you want share constants, you can add a Shared Project and reference the Shared Project into project1 and project2. The code in the Shared Project (a static class with constants members) is linked into other projects :

    public static class Constants
    {
        const string AppName = "AppName";
        const string AppUrl = "http://localhost:1234/myurl";
        const int SomethingCount = 3;
    }
    

    If you want share runtime variables (with dynamic values), you can add a Class Library or a PCL and reference it into project1 and project2. The code in the Class Library will be compiled in a DLL and shared between other projects. You can create a class with static members and share your runtime variables by this way :

    public static class RuntimeValues
    {
        public static string AppName { get; set; }
        public static string AppUrl { get; set; }
        public static int SomethingCount { get; set; }
    }
    

    In your project1 and project2, you can do something like :

    var appName = Constants.AppName;
    

    Or :

    RuntimeValues.AppName = "AppName";
    var appName = RuntimeValues.AppName;