473,545 Members | 2,388 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do you get the default value of a Constant using reflection in c#?

maf
Using reflection, I'm trying to get the value for a constant in an enum.
Getting the contant name works fine using:

FieldInfo[] fieldInfos = TYPE.GetFields( );

foreach(FieldIn fo fi in fieldInfos )
{

Console.WriteLi ne("Name: {0}" fi.Name);
Console.WriteLi ne("Value: {0} " fi.GetValue(nul l).ToString());
}

This write:
Name: myFieldName
Value: myFieldName

I want:
Name: myFieldName
Value: 6

Thanks,
mf
Nov 15 '05 #1
7 6360
maf wrote:
Using reflection, I'm trying to get the value for a constant in an enum.
Getting the contant name works fine using:

FieldInfo[] fieldInfos = TYPE.GetFields( );

foreach(FieldIn fo fi in fieldInfos )
{

Console.WriteLi ne("Name: {0}" fi.Name);
Console.WriteLi ne("Value: {0} " fi.GetValue(nul l).ToString());
}

This write:
Name: myFieldName
Value: myFieldName

I want:
Name: myFieldName
Value: 6

Thanks,
mf


Convert the enum value to an int instead of a string:

Console.WriteLi ne("Value: {0}", (int) fi.GetValue(nul l));
--
mikeb
Nov 15 '05 #2
mikeb wrote:
maf wrote:
Using reflection, I'm trying to get the value for a constant in an enum.
Getting the contant name works fine using:

FieldInfo[] fieldInfos = TYPE.GetFields( );

foreach(FieldIn fo fi in fieldInfos )
{

Console.WriteLi ne("Name: {0}" fi.Name);
Console.WriteLi ne("Value: {0} " fi.GetValue(nul l).ToString());
}

This write:
Name: myFieldName
Value: myFieldName

I want:
Name: myFieldName
Value: 6

Thanks,
mf

Convert the enum value to an int instead of a string:

Console.WriteLi ne("Value: {0}", (int) fi.GetValue(nul l));


A slightly more correct but complex form (which won't break if the
underlying enum type can't be cast into an int):

Console.WriteLi ne("real value: {0}",
Convert.ChangeT ype( fi.GetValue(nul l),
Enum.GetUnderly ingType( fi.FieldType))) ;
--
mikeb
Nov 15 '05 #3

Hi mf,

Thank you for using MSDN Newsgroup! My name is Jeffrey, and I will be
assisting you on this issue.
Based on my understanding, you want to use .Net Reflection to get some
information of your enumeration(Suc h as string representaion, value, type,
etc..)

=============== =============== =============== ===
Actually, FieldInfo.GetVa lue will return the an object which is a type of
your enumeration. And FieldInfo.GetVa lue().ToString( ) will default return
the string representation of your enumeration value(That is the field
name). To get the actual int value of your enumeration, you can just
explicit convert your enumeration to int type.

You can try the following 2 Solutions to see if it helps resolve your issue:
enum test
{
test1=1,
test2=55,
test3=67,
test4=89
};

First Solution(Use Enumeration class methods):
string [] names=Enum.GetN ames(typeof(tes t));
for(int i=0;i<names.Len gth;i++)
{
Console.WriteLi ne(names[i]);
}

Array arr=Enum.GetVal ues(typeof(test ));
for(int i=0;i<arr.Lengt h;i++)
{
Console.WriteLi ne(((int)arr.Ge tValue(i)).ToSt ring());
}

Second Solution(Use Reflection):
Type t=typeof(test);
FieldInfo [] fis=t.GetFields ();
foreach(FieldIn fo fi in fis)
{
if(fi.Name!="va lue__")
{
object obj=fi.GetValue (null);
Console.WriteLi ne(((int)obj).T oString());
}
}
Note: Use reflection, you will get the 5 fieldinfo objects instead of 4.
Because it will get an internal object in fis[0](Its name is value__), we
just jump over this object.

=============== =============== ===========
Please apply my suggestion above and let me know if it helps resolve your
problem.

Thank you for your patience and cooperation. If you have any questions or
concerns, please feel free to post it in the group. I am standing by to be
of assistance.
Hope you have a nice experience in Microsoft Newsgroup!

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #4
100
Hi maf,
You can get that info using Enum class members.

HTH
B\rgds
100

"maf" <mf*********@pr oclarity.com> wrote in message
news:9c******** *************** ***@posting.goo gle.com...
Using reflection, I'm trying to get the value for a constant in an enum.
Getting the contant name works fine using:

FieldInfo[] fieldInfos = TYPE.GetFields( );

foreach(FieldIn fo fi in fieldInfos )
{

Console.WriteLi ne("Name: {0}" fi.Name);
Console.WriteLi ne("Value: {0} " fi.GetValue(nul l).ToString());
}

This write:
Name: myFieldName
Value: myFieldName

I want:
Name: myFieldName
Value: 6

Thanks,
mf

Nov 15 '05 #5
Jeff,
Thanks for the reply. Before I got this(which worked as
well), I had found that
fi.GetValue(nul l).GetHashCode( ));
worked.
But don't you think that GetValue() should implicitely
retun a value, not an object?
Thanks for your time.
-mf
Nov 15 '05 #6
100
Hi,
The most convenient way to work with enumerators , I believe, is to use Enum
class members as I suggested.
However you can get the value using reflection as well.
fi.GetValue(nul l) returns object of eunumerations type.
For example
enum MyEnum {First = 100, Sec}
Type t = typeof(MyEnum);
FieldInfo fi = t.GetField("Fir st");
object val = fi.GetValue(nul l);

at this point we have val set to an object, which actual type is MyEnum. If
I try to do val.ToString() I'll get the string "First" because that's how
enum's ToString method works.
However enums have underlaying type and enum objects can be cast to them. In
my case underlaying type is int
so I can do
((int)val).ToSt ring(); and this will give me the string "100".
If it has to work in all casses underalying type doesn't have to be
hardcoded. Some of the method of more safe type casting should be used.

HTH
B\rgds
100
<an*******@disc ussions.microso ft.com> wrote in message
news:14******** *************** *****@phx.gbl.. .
Jeff,
Thanks for the reply. Before I got this(which worked as
well), I had found that
fi.GetValue(nul l).GetHashCode( ));
worked.
But don't you think that GetValue() should implicitely
retun a value, not an object?
Thanks for your time.
-mf

Nov 15 '05 #7

Hi MF,

Thanks very much for your feedback.
I am glad my reply makes sense to you. I think your further is that: Why
FieldInfo.GetVa lue() not return a "value" but an object type.

=============== =============== ===============
Actually, FieldInfo class discovers the attributes of a field and provides
access to field metadata. It is a common usage class for class fields, not
special for Enum.
For other class, its fields may be of any other types, so the only suitable
type to refer the return value of FieldInfo.GetVa lue is System.Object.( If
the field is primitive type, it will get boxed to reference type)

So I recommand you to use Enum.GetValues( ) method to do this, because it is
specially for Enumeration. The Enum.GetValues( ) will return an array
objects with the type of your enumeration. System.Enum inherited from
System.ValueTyp e which is all the value type's base class.

=============== =============== ===============

If you still have anything unclear, please feel free to tell me, I will
work with you.
Have a nice day!

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

46
3465
by: J.R. | last post by:
Hi folks, The python can only support passing value in function call (right?), I'm wondering how to effectively pass a large parameter, such as a large list or dictionary? It could achieved by pointer in C++, is there such way in Python? Thansk in advance. J.R.
2
830
by: CMan | last post by:
Hi All, I am trying to use a COM component that has methods with default parameters. How can I call these methods from C#. Not all default values are in the documentation of the control. Thanks Colin
4
5833
by: aling | last post by:
What's the rule of default argument of function in C++? I found that the default argument of function could not necessary be a constant value. Is it true? Previously I thought that the default argument of function must be a constant value. Here is my sample code, it's compiled successully in VC7.1. #include<iostream> class Base{ public :
4
10063
by: Brian Brane | last post by:
I have properties that wrap DataRow columns as in: public int aNumber { get{ return m_DataRow; } set{ m_DataRow = value; } } If the column happens to contain DBNull, I get a cast exception since DBNull cannot be converted to int. I wrote the following method that looks up the column's data type and if it is a ValueType, returns the...
29
3024
by: John Wood | last post by:
Even though CSC does its best to detect use of unassigned variables, it often misses it... for example if you just declare a double in a class without assigning a default value, it has a default value of 0 and lets you use it anyway. My question is, how can I retrieve the default value for a given type? The CLR obviously has these defaults...
12
2674
by: Edward Diener | last post by:
Given value class X { public: // Not allowed: X():i(100000),s(10000) { } // Allowed void InitializeDefaults() { i = 100000; s = 10000; } private: int i;
12
2302
by: aaragon | last post by:
Hello all. I have a simple question that seems trivial but I can't make it to work. I have a class that takes as a template argument, another class. The idea is as follows: #include <iostream> using namespace std; template <class ClassB> class ClassA
9
5038
by: Eric | last post by:
Hi Everyone, I'm writing a UserControl that exposes a property of the type System.Drawing.Image, like this: Public Property DefaultImage() As Image Get Return propDefaultImage End Get Set(ByVal Value As Image)
4
1315
by: Gordon | last post by:
I'm trying to get a constant from a class, where the constant's name is known, but the class name isn't. I want to do things this way because I want classes to be able to define certain aspects for their setup themselves. For example: I have a situation where I have a script that can deal with objects of one of several classes, but each...
0
7487
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7420
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7680
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7934
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7446
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7778
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6003
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
1033
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
731
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.