Click here to Skip to main content
Click here to Skip to main content

Tagged as

Getting enum value from another class via Reflection in C#.NET

, 21 Feb 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Get Enum value from another class through the object.

Introduction

Reflection is the process by which a computer program can observe and modify its own structure and behavior. Assemblies contain modules, modules contain types, and types contain members. Reflection provides objects that encapsulate assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object. You can then invoke the type's methods or access its fields and properties. Typical uses of reflection are details here.

Getting members of an Enum via reflection 

It’s very simple to get the value when enum value taken from same class. In this code enum value has to provide for getting type and the type object can supply the field with GetFields() method. Here the GetFields() method works for reflection. 

Look at this example, 

static void Main(string[] args)
{
    Type enumType = typeof(EnumName);
    FieldInfo[] infos;
    Infos = enumType.GetFields();
    infos = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
    foreach (FieldInfo fi in infos)
    {
        Console.WriteLine(fi.Name);
    }
}  
But what should we do when the enum accessed from different class? In that case we have to use reflection. Because reflection can provides method, constructor, type of another class or assembly.

My main purpose is not to get the value from same class, I will show how to get enum value from another class and with dynamic class object. I mention dynamic because I can choose class any class and takes the object then getting the enum value through the class object. OK, let’s start the discussion how the code is working. GetMembers() is another reflection method which returns the public or static method as MemberInfo[]

Suppose I have a class as ClassOne then I can get all the methods using the reflection method.

 using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ReflectionEnum
{
    public class ClassOne
    {
        public enum EnumName1
        {
            OneValue = 1,
            TwoValue = 2,
            ThreeValue = 3,
            FourValue = 4
        }
        public enum EnumName2
        {
            FiveValue = 500,
            SixValue = 600,
            SevenValue = 700,
            EightValue = 800
        }
    }
}

In that case If I want the enum names then:

Object dynamicObject=new ClassOne();
//get common type 
Type dynamicType = dynamicObject.GetType();
//get member info
MemberInfo[] memberInfos = dynamicType.GetMembers(BindingFlags.Public | BindingFlags.Static);

I could use the class name directly for getting type but here I used to show how to get the type in dynamic selection.

Now, all the methods are now in memberInfos variable. So all the enum name can find if foreach use like this:

foreach (MemberInfo t in memberInfos)
{
   Console.WriteLine(t.Name);
} 

Output:

EnumName1ClassOne
EnumName2ClassOne 

But I needs the values of enum then again I need to use reflection and get the type of enum but problem is I have to get the type from Enum name. But its not possible to get type using GetType() method with enum name only. For that I had to use the Namespace, class then enum name like this format: 

var typeEnums = System.Type.GetType(“Namespace Name” + "." + “Class Name” + "+" + “Enum Name”);

Now it’s very easy to get the enum value’s from typeEnums using GetFields() method.

var fieldsArray = typeEnums.GetFields(BindingFlags.Public | BindingFlags.Static);

foreach (var fInfo in fieldsArray)
{
    var ulngValue = (ulong)Convert.ChangeType(fInfo.GetValue(null), typeof(ulong));
    Console.WriteLine(fInfo.Name.ToString(CultureInfo.InvariantCulture) + ":" + ulngValue.ToStr    ing(CultureInfo.InvariantCulture));
}   

At last my desired output comes:

EnumName1ClassOne 

OneValue : 1
TwoValue : 2
ThreeValue : 3
FourValue : 4
EnumName2ClassOne
FiveValue : 500
SixValue : 600
SevenValue : 700
EightValue : 800  

History

  • 21-February-2013

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


Comments and Discussions

 
QuestionHow to give namespace, class name and PinmemberKumaresh V C23-Feb-13 1:17 
QuestionWhat is Rationale behind getting enum value? PingroupExcellentOrg22-Feb-13 19:18 
SuggestionReally doing it the hard way! [modified] PinmemberMatt T Heffron21-Feb-13 13:30 
GeneralRe: Really doing it the hard way! PinmemberMd. Humayun Rashed21-Feb-13 17:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.141022.1 | Last Updated 21 Feb 2013
Article Copyright 2013 by Md. Humayun Rashed
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid