Exemplo n.º 1
0
        static void Main(string[] args)
        {
            Console.WriteLine("*** Fun with Enums ***\n");
            // Создать переменную типа EmpType
            EmpType emp = EmpType.Contractor; // !!! Перед значением нужно указывать имя перечисления
            AskForBonus(emp);

            // Показать тип перечисления (=> FunWithEnums.EmpType)
            Console.WriteLine("GetType() = {0}", emp.GetType()); // для переменной
            Console.WriteLine("typeof() = {0}", typeof(EmpType));// для самого перечисления


            // Вывести текущее строковое имя перечисления
            Console.WriteLine("emp is a {0}.", emp.ToString());
            // Вывести не имя, а значение заданной переменной перечисления => нужно привести ее к текущему типу хранения
            Console.WriteLine("{0} = {1}", emp.ToString(), (int)emp);
            // Вывести тип хранилища для значений перечисления.
            Console.WriteLine("EmpType uses a {0} for storage(using Enum.GetUnderlyingType())",
                Enum.GetUnderlyingType(emp.GetType())); 
            //На этот раз для получения информации о типе используется операция typeof.
            Console.WriteLine("EmpType uses a {0} for storage(using typeof)",
            Enum.GetUnderlyingType(typeof(EmpType)));

            // Enum’s Name-Value Pairs
            EmpType e2 = EmpType.Grunt;
            // Эти типы являются перечислениями из пространства имен System.
            DayOfWeek day = DayOfWeek.Monday;
            ConsoleColor cc = ConsoleColor.Gray;

            EvaluateEnum(e2);
            EvaluateEnum(day);
            EvaluateEnum(cc);

            Console.ReadLine();
        }
Exemplo n.º 2
0
        static void AskForBonus(EmpType e)
        {
            switch (e)
            {
            case EmpType.Manager:
                Console.WriteLine("How about stock options  instead");
                Console.WriteLine("The type is : {0}", e.GetType().Name);
                break;

            case EmpType.Grunt:
                Console.WriteLine("You have got to be kidding...");
                Console.WriteLine("The type is : {0}", e.GetType().Name);
                break;

            case EmpType.Contractor:
                Console.WriteLine("You already get enough cash...");
                Console.WriteLine("The type is : {0}", e.GetType().Name);
                break;

            case EmpType.VicePresident:
                Console.WriteLine("Very good Sir...");
                Console.WriteLine("The type is : {0}", e.GetType().Name);
                break;
            }
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            EmpType emp = EmpType.Contracrot;

            Console.WriteLine($"{Enum.GetUnderlyingType(emp.GetType())}");
            Console.WriteLine($"{emp.GetType()}");
            Show();
            Console.WriteLine("Hello World!");
        }
Exemplo n.º 4
0
        public void enum_usage()
        {
            // 1. use as variable
            EmpType emp = EmpType.Contractor;

            // 2. get type
            Console.WriteLine(emp.GetType().Name);
            Console.WriteLine(emp.ToString());            // output "Contractor"
            // 3. Enum.GetValues
            Array enumData = Enum.GetValues(emp.GetType());
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            Console.WriteLine("**** Fun with Enums *****");
            // Make a contractor type.
            EmpType emp = EmpType.Contractor;

            AskForBonus(emp);

            // Print storage for the enum.
            Console.WriteLine("EmpType uses a {0} for storage",
                              Enum.GetUnderlyingType(emp.GetType()));
            Console.WriteLine("EmpType uses a {0} for storage",
                              Enum.GetUnderlyingType(typeof(NonSequentialEmpType))); // No instance is used

            // Get all name/value pairs for enum.
            Array enumData = Enum.GetValues(typeof(EmpType));

            Console.WriteLine("This enum has {0} members.", enumData.Length);
            // Now show the string name and associated value, using the D format
            // flag (see Chapter 3).
            for (int i = 0; i < enumData.Length; i++)
            {
                Console.WriteLine("Name: {0}, Value: {0:D}",
                                  enumData.GetValue(i));
            }
        }
Exemplo n.º 6
0
        private static void FuckWithEnum()
        {
            System.Console.WriteLine("***** F**k With Enums *****");

            EmpType emp = EmpType.Contractor;

            AskForBonus(emp);

            System.Console.WriteLine($"EmpType uses a {emp.GetType()} for storage");
        }
Exemplo n.º 7
0
        /// <summary>
        /// print out all information for Enum
        /// </summary>
        public void EnumInfo()
        {
            EmpType e = EmpType.Manager;

            Console.WriteLine("Enum Name: " + e.GetType().Name);
            Console.WriteLine("Underlying storage type: {0}",
                              Enum.GetUnderlyingType(e.GetType()));

            Array enumData = Enum.GetValues(e.GetType());

            Console.WriteLine("This enum has {0} members.", enumData.Length);

            // Now show the string name and associated value.
            for (int i = 0; i < enumData.Length; i++)
            {
                Console.WriteLine("Name: {0}, Value: {0:D}",
                                  enumData.GetValue(i));
            }
            Console.WriteLine();
        }
Exemplo n.º 8
0
        static void Enums()
        {
            Console.ForegroundColor = ConsoleColor.Green;
            EmpType emp = EmpType.Contractor;

            AskForBonus(emp);

            Console.WriteLine("EmpType uses a {0} for storage.", Enum.GetUnderlyingType(emp.GetType()));
            Console.WriteLine("emp: Type (metadata description) is {0} / {1}",
                              emp.GetType(), typeof(EmpType));
            Console.WriteLine("emp: name is {0} (string name), value is {1}",
                              emp.ToString(), (byte)emp);
            Console.WriteLine("The value of {0} is {1} / {2}h", emp.ToString(),
                              Enum.Format(typeof(EmpType), emp, "d"), Enum.Format(typeof(EmpType), emp, "x"));
            Console.WriteLine();
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            Console.WriteLine("=> Fun with Enums");
            EmpType emp = EmpType.Contractor;

            AskForBonus(emp);
            //using GetType method
            Console.WriteLine("EmpType uses {0} for storage", Enum.GetUnderlyingType(emp.GetType()));
            //using typeof method
            Console.WriteLine("EmpType uses {0} for storage", Enum.GetUnderlyingType(typeof(EmpType)));

            Console.WriteLine("Emp is a {0} ", emp.ToString());

            //print out enum name and value
            Console.WriteLine("{0} = {1}", emp.ToString(), (byte)emp);
            DayOfWeek    day = DayOfWeek.Monday;
            ConsoleColor cc  = ConsoleColor.Gray;

            EvaluateEnum(day);
            Console.ReadKey();
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            Console.WriteLine("**** Fun with Enums *****");
            // Make an EmpType variable.
            EmpType emp = EmpType.Contractor;

            AskForBonus(emp);


            // Print storage for the enum.
            Console.WriteLine("EmpType uses a {0} for storage",
                              Enum.GetUnderlyingType(emp.GetType()));

            // This time use typeof to extract a Type.
            Console.WriteLine("EmpType uses a {0} for storage",
                              Enum.GetUnderlyingType(typeof(EmpType)));

            // Prints out "emp is a Contractor".
            Console.WriteLine("emp is a {0}.", emp.ToString());


            // Prints out "Contractor = 100".
            Console.WriteLine("{0} name's value = {1}", emp.ToString(), (byte)emp);


            EmpType e2 = EmpType.Contractor;

            // These types are enums in the System namespace.
            DayOfWeek    day = DayOfWeek.Monday;
            ConsoleColor cc  = ConsoleColor.Gray;

            EvaluateEnum(e2);
            EvaluateEnum(day);
            EvaluateEnum(cc);

            Console.ReadLine();
        }
Exemplo n.º 11
0
        public static void TestEnums()
        {
            #region enum instances methods


            EmpType emp1 = EmpType.Manager;
            // ------------------------<  obj.ToString()  >------------------------
            Console.WriteLine(emp1);
            Console.WriteLine($"emp1.ToString() = {emp1.ToString()}");

            // ------------------------<  obj.GetType()  >------------------------
            Console.WriteLine($"emp1.GetType() = {emp1.GetType()}");    //pro_csharp_book_training.EmpType

            // ------------------------<  obj.GetTypeCode()  >------------------------
            Console.WriteLine($"emp1.GetTypeCode() = {emp1.GetTypeCode()}");    //Int32

            // ------------------------<  obj.CompareTo(object target)  >------------------------
            // NOTE: target argument should be in the same type of enumeration
            Console.WriteLine($"emp1.CompareTo(EmpType.Manager) = {emp1.CompareTo(EmpType.Manager)}");         // 0
            Console.WriteLine($"emp1.CompareTo(EmpType.SalesPersom) = {emp1.CompareTo(EmpType.SalesPersom)}"); // -1
            //Error:passing string not EmptType
            //Console.WriteLine($@"emp1.CompareTo(""Manager"") = {emp1.CompareTo("Manager")}");
            //Error:passing int not EmptType
            //Console.WriteLine($"emp1.CompareTo(0) = { emp1.CompareTo(0)}");

            // ------------------------<  obj.Equals(object target)  >------------------------
            // Equals : it accepts underline storage or enum constant name,
            //          so it doesn't throw Exception in Type Mismatch
            Console.WriteLine($"emp1.Equals(EmpType.Manager) = {emp1.Equals(EmpType.Manager)}");         // True
            Console.WriteLine($"emp1.Equals(EmpType.SalesPersom) = {emp1.Equals(EmpType.SalesPersom)}"); // False
            Console.WriteLine($"emp1.Equals(1) = {emp1.Equals(1)}");                                     // False
            Console.WriteLine($@"emp1.Equals(""Managers"") = {emp1.Equals("Manager")}");                 // False
            #endregion

            #region Get Type of enum
            // ------------------------<  System.Enum Class Functionality  >------------------------
            // -------------------------------------------------------------------------------------
            Console.WriteLine($"Enum.GetUnderlyingType(typeof(EmpType)) = {Enum.GetUnderlyingType(typeof(EmpType))} "); // Int32
            #endregion

            #region Array Enum.GetValues(Type enumtype);

            // ------------------------<   public static Array GetValues(Type enumType);  >------------------------
            Console.WriteLine("1- Array empItems = Enum.GetValues(typeof(EmpType))");
            Array empItems = Enum.GetValues(typeof(EmpType));
            foreach (EmpType item in empItems)
            {
                Console.WriteLine($"Name: {item} , Value: {(int)item}");
            }
            Console.WriteLine();


            // ------------------------<  public static Array GetValues(Type enumType);  >------------------------
            // The same as the last code but here we see some changes
            Console.WriteLine("2- Array empItems = Enum.GetValues(typeof(EmpType))");
            empItems = Enum.GetValues(typeof(EmpType));
            for (int i = 0; i < empItems.Length; i++)
            {
                Console.WriteLine("Name: {0} , Value: {0:D}", empItems.GetValue(i));
            }
            Console.WriteLine();

            // ------------------------<  public static Array GetValues(Type enumType);  >------------------------
            // The same as the last code but here we see some changes
            Console.WriteLine("3- Enum.GetValues(emp1.GetType())");
            foreach (EmpType item in Enum.GetValues(emp1.GetType()))
            {
                //Console.WriteLine($"Name: {item} , Value: {(int)item}");
                Console.WriteLine("Name: {0} , Value: {1}", item, (int)item);
            }
            Console.WriteLine();
            #endregion

            #region public static string[] GetNames(Type enumType)
            // ------------------------<  public static string[] GetNames(Type enumType);  >------------------------
            Console.WriteLine("Enum.GetNames()");
            foreach (string item in Enum.GetNames(typeof(EmpType)))
            {
                Console.WriteLine($"{item}");
            }
            Console.WriteLine();
            #endregion

            #region public static string GetName(Type enumType, object value);
            // ------------------------<  public static string GetName(Type enumType, object value);  >------------------------
            Console.WriteLine("Enum.GetName(typeof(EmpType),0) = {0}", Enum.GetName(typeof(EmpType), 0));
            #endregion

            #region public static object Parse(Type enumType, string value);
            // ------------------------<  public static object Parse(Type enumType, string value);  >------------------------
            Console.WriteLine("public static object Parse(Type enumType, string value);");
            emp1 = EmpType.SalesPersom;
            Console.WriteLine(emp1.ToString());
            emp1 = (EmpType)Enum.Parse(typeof(EmpType), "Manager");
            Console.WriteLine(@"Enum.Parse(typeof(EmpType),""Manager"") = " + emp1);

            emp1 = (EmpType)Enum.Parse(typeof(EmpType), "2");
            Console.WriteLine(@"Enum.Parse(typeof(EmpType),""2"") = " + emp1);
            #endregion

            #region public static bool TryParse<TEnum>(string value, out TEnum result) where TEnum : struct;
            // -----<  public static bool TryParse<TEnum>(string value, out TEnum result) where TEnum : struct;  >------

            if (Enum.TryParse("PTSalesPerson", out EmpType emp2))
            {
                Console.WriteLine($"TryParse string (PTSalesPerson) Result:");
                WriteEnum(emp2);
            }
            else
            {
                Console.WriteLine("Can't Parse string");
            }

            if (Enum.TryParse("2", out emp2))
            {
                Console.WriteLine($"TryParse integer 2 Result:");
                WriteEnum(emp2);
            }
            else
            {
                Console.WriteLine("Can't Parse integer");
            }
            #endregion

            #region public static object ToObject(Type enumType, int value);
            // -----<  public static object ToObject(Type enumType, int value);  >------
            Console.WriteLine(new StringBuilder().Append('=', 30));
            Console.WriteLine("public static object ToObject(Type enumType, int value);");
            // To convert integer any provided value type to enum
            EmpType emp3 = (EmpType)Enum.ToObject(typeof(EmpType), 2);
            WriteEnum(emp3);
            WriteEnumNameValuePair(emp3.GetType());
            #endregion

            #region public static bool IsDefined(Type enumType, object value);


            // -----<  public static bool IsDefined(Type enumType, object value);  >------
            Console.WriteLine();
            Console.WriteLine("public static bool IsDefined(Type enumType, object value);");
            Console.WriteLine($@"Enum.IsDefined(typeof(Day),""Sat"") = {Enum.IsDefined(typeof(Day),"Sat")}");
            Console.WriteLine($@"Enum.IsDefined(typeof(Day),""sat"") = {Enum.IsDefined(typeof(Day), "sat")}");
            Console.WriteLine($@"Enum.IsDefined(typeof(Day),""Moamen"") = {Enum.IsDefined(typeof(Day), "Moamen")}");
            Console.WriteLine();
            #endregion

            #region public static string Format(Type enumType, object value, string format);
            //-----<  public static string Format(Type enumType, object value, string format);  >------
            //  Format          Description
            //"G" or "g"        If value is equal to a named enumerated constant,
            //                  the name of that constant is returned; otherwise,
            //                  the decimal equivalent of value is returned.

            //                  For example, suppose the only enumerated constant is named Red,
            //                  and its value is 1.If value is specified as 1, this format returns "Red".However,
            //                  if value is specified as 2, this format returns "2".
            ///////////////// there are another part here in Microsoft APIs about FlagsAttribute.

            // "X" or "x"       Represents value in hexadecimal format without a leading "0x".

            // "D" or "d"       Represents value in decimal form.

            // "F" or "f"       Behaves identically to "G" or "g", except that
            //                  the FlagsAttribute is not required to be present on the Enum declaration.
            Console.WriteLine("------------------- General Format --------------------");
            Console.WriteLine($@"Enum.Format(Day, Day.Sat,""G"") = {Enum.Format(typeof(Day), Day.Sat, "G")}");
            Console.WriteLine($@"Enum.Format(Day, Day.Sun,""G"") = {Enum.Format(typeof(Day), Day.Sun, "G")}");
            Console.WriteLine($@"Enum.Format(Day, Day.Mon,""G"") = {Enum.Format(typeof(Day), Day.Mon, "G")}");

            Console.WriteLine("------------------- Decimal Format --------------------");
            Console.WriteLine($@"Enum.Format(Day, Day.Sat,""D"") = {Enum.Format(typeof(Day), Day.Sat, "D")}");
            Console.WriteLine($@"Enum.Format(Day, Day.Sun,""D"") = {Enum.Format(typeof(Day), Day.Sun, "D")}");
            Console.WriteLine($@"Enum.Format(Day, Day.Mon,""D"") = {Enum.Format(typeof(Day), Day.Mon, "D")}");

            Console.WriteLine("------------------- HexDecimal Format --------------------");
            Console.WriteLine($@"Enum.Format(Day, Day.Sat,""x"") = {Enum.Format(typeof(Day), Day.Sat, "x")}");
            Console.WriteLine($@"Enum.Format(Day, Day.Sun,""x"") = {Enum.Format(typeof(Day), Day.Sun, "x")}");
            Console.WriteLine($@"Enum.Format(Day, Day.Mon,""x"") = {Enum.Format(typeof(Day), Day.Mon, "x")}");
            #endregion

            // Test: public static void WriteEnumNameValuePair(Type enumType);
            WriteEnumNameValuePair(emp2.GetType());
            WriteEnumNameValuePair(typeof(Day));
        }
Exemplo n.º 12
0
        private static void Main(string[] args)
        {
            Console.WriteLine("***** Fun with Enums *****");
            EmpType emp = EmpType.Contractor;

            AskForBonus(emp);
            Console.WriteLine("EmpType uses a {0} for storage", Enum.GetUnderlyingType(emp.GetType()));
            Console.WriteLine("EmpType uses a {0} for storage", Enum.GetUnderlyingType(typeof(EmpType)));
            Console.WriteLine("emp is a {0}.", emp.ToString());
            Console.WriteLine("{0} = {1}", emp.ToString(), (byte)emp);
            Console.WriteLine();

            EmpType      e2  = EmpType.Contractor;
            DayOfWeek    day = DayOfWeek.Monday;
            ConsoleColor cc  = ConsoleColor.Gray;

            EvaluateEnum(e2);
            EvaluateEnum(day);
            EvaluateEnum(cc);
            Console.ReadLine();

            Console.WriteLine();
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            Console.WriteLine("**** Fun with enums ****");
            EmpType emp = EmpType.Contractor;

            AskForBonus(emp);

            Console.WriteLine("EmpType uses a {0} as storage", Enum.GetUnderlyingType(emp.GetType()));
            Console.WriteLine("emp name is {0}, and value: {1}", emp.ToString(), Enum.Format(emp.GetType(), emp, "D"));
            DayOfWeek    dw = DayOfWeek.Monday;
            ConsoleColor cc = ConsoleColor.Red;

            EvaluateEnum(emp);
            EvaluateEnum(dw);
            EvaluateEnum(cc);
            Console.ReadLine();
        }
Exemplo n.º 14
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Enums...");
            //contractor type

            EmpType emp = EmpType.Contractor;            //emp --> Contractor

            AskForBonus(emp);

            Console.WriteLine("EmpType uses a {0} for storage\n", Enum.GetUnderlyingType(emp.GetType()));

            Console.WriteLine("emp is AccessViolationException {0} for storage\n", Enum.GetUnderlyingType(typeof(EmpType)));

            Console.WriteLine("emp is a {0}\n", emp.ToString());

            Console.WriteLine("{0} = {1}\n", emp.ToString(), (byte)emp);

            EmpType e2 = EmpType.Contractor;

            DayOfWeek    day   = DayOfWeek.Monday;
            ConsoleColor color = ConsoleColor.DarkGray;

            EvaluateEnum(e2);
            EvaluateEnum(day);
            EvaluateEnum(color);
            Console.ReadLine();
        }
Exemplo n.º 15
0
 /// <summary>
 /// Existem duas formas de obter o tipo de armazenamento de um enum
 /// emp.GetType
 /// or
 /// typeof(EmpType)
 /// </summary>
 /// <param name="emp"></param>
 private static void PrintStorageEnum(EmpType emp)
 {
     Console.WriteLine("EmpType uses a {0} for storage", Enum.GetUnderlyingType(emp.GetType()));
     Console.WriteLine("EmpType uses a {0} for storage", Enum.GetUnderlyingType(typeof(EmpType)));
     Console.WriteLine("\n");
 }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            //fiddling
            EmpType emp = EmpType.Contractor;

            Console.WriteLine("EmpType uses {0} for storage (typeof on class)", Enum.GetUnderlyingType(typeof(EmpType)));
            Console.WriteLine("EmpType uses {0} for storage (.GetType on instance)", Enum.GetUnderlyingType(emp.GetType()));

            Console.WriteLine("Enum vital statistics");
            EvaluateEnum(emp);
            EvaluateEnum(DayOfWeek.Monday);
            EvaluateEnum(ConsoleColor.Black);

            Console.ReadLine();
        }