Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Enum.GetName() ask for a Type when this information is passed with the object parameter?

Consider the .NET function signature:

Enum.GetName(Type type, object o);

Is seems entirely unnecessary to ask for the Type when this information is passed with object o

The following code illustrates this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public enum Color
    {
        Black, White, Red, Orange, Yellow, Green, Blue, Purple, Pink,
        DarkRed, DarkGreen, DarkBlue,
        NeonGreen, NeonBlue
    }
    class Program
    {
        private static Random rand = new Random();

        static void Main(string[] args)
        {
            Color color = getRandomColor();
            PrintType(color);
            Console.WriteLine("typeof = " + typeof(Color));
            Console.ReadLine();
        }

        public static void PrintType(object o) 
        {
            Type type = o.GetType();
            Console.WriteLine("type = " + type);
        }

        private static Color getRandomColor()
        {
            var values = Enum.GetValues(typeof(Color));
            Color randomColor = (Color)values.GetValue(rand.Next(values.Length));
            return randomColor;
        }
    }
}

The output is

type = ConsoleApplication1.Color
typeof = ConsoleApplication1.Color

Which means that the Enum.GetName() method signature could look like this instead:

Enum.GetName(object o);
like image 366
Nikolaii99 Avatar asked Dec 15 '22 18:12

Nikolaii99


1 Answers

o does not need to be of type Color. Example:

Enum.GetName(typeof(Color), 3) // == Orange
like image 146
Sebastian Negraszus Avatar answered May 25 '23 09:05

Sebastian Negraszus