locked
How to call Cnn & Gender in other classes RRS feed

  • Question

  • User1979860870 posted

    Hi

      How to call Cnn in other classes

    namespace Employee_Management.Models
    {
        public class Common
        {
            public SqlConnection Cnn;
            
            public enum Gender
            {
                Male,
                Female,
                Other
            }
    }
    }

    Thanks

    Saturday, January 16, 2021 6:58 AM

Answers

  • User475983607 posted

    How to call Cnn in other classes

    Using a property is the normal design approach.   Properties - C# Programming guide

        public class Common
        {
            public SqlConnection Cnn { get; set; }
    
            public enum Gender
            {
                Male,
                Female,
                Other
            }
        }
        class Program
        {
    
            static void Main(string[] args)
            {
                Common common = new Common() { Cnn = new SqlConnection("Data Source=blogging.db") };
                Console.WriteLine(common.Cnn.ConnectionString);
                Console.WriteLine(Common.Gender.Female);
            }
        }

    Enums are named constants.  Enumeration types (C# reference)

    In your unusual design, the enum is accessed accessed through the class.  Typically, enums are placed within a namespaces not a class.  This same advice was given in another one of your threads with the same subject.

    I think you might be after the following pattern.

    namespace ConsoleAppCS
    {
        public enum Gender
        {
            Male,
            Female,
            Other
        }
    
        public class Common
        {
            public SqlConnection Cnn { get; set; }
            public Gender Gender { get; set; }
    
        }
        class Program
        {
    
            static void Main(string[] args)
            {
                Common common = new Common() { 
                    Cnn = new SqlConnection("Data Source=blogging.db"),
                    Gender = Gender.Male
                };
    
                Console.WriteLine(common.Cnn.ConnectionString);
                Console.WriteLine(common.Gender);
            }
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, January 16, 2021 1:31 PM