How to access static properties in an object in C#

1 Answer

0 votes
using System;

namespace StaticPropertyExample
{
    public static class Configuration
    {
        // Define a private backing field for the static property
        private static string _environment = "production";

        // Public static property with encapsulation and validation logic
        public static string Environment
        {
            get => _environment;
            set
            {
                if (!string.IsNullOrWhiteSpace(value)) {
                    _environment = value;
                }
            }
        }

        // A static function that utilizes the static property
        public static string GetEnvironmentDetails()
        {
            return $"Active environment status: {_environment}";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // 1. Accessing a static property directly via the Class Name (Best Practice)
            Console.WriteLine(Configuration.Environment);

            // 2. Calling a static function that reads the static property
            Console.WriteLine(Configuration.GetEnvironmentDetails());

            // 3. Modifying the static property
            Configuration.Environment = "staging";
            Console.WriteLine($"Updated Environment: {Configuration.Environment}");
        }
    }
}


/*
run:

production
Active environment status: production
Updated Environment: staging

*/

 



answered Oct 31 by avibootz
...