473,785 Members | 2,282 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to use reflection & Enums in C# 2.0

I have a class holding some enumerated types, i.e.,

public class MyEnums
{
public enum DATA_ITEM {FIRST, SECOND, THIRD,FOURTH,FI FTH};
...
}

And I have a class the contains data, for example:

public class TheData
{
double a, b, c;
int d,e;

...
}
public class MyDataClass
{
List<TheData> myData;

public List<TheData> MYDATA
{
get {return myData; }
...
}
...
}
I want to write a utility function as follows

public class Utility {

private double adder (List<TheData> data, FIELD fld) --> ???
{
double val = 0.0;
foreach (...)
{
val += data.fld; --> ????
}
}
public static SUM_DATA (MyDataClass mdc, MyEnums.DATA_IT EM di)
{

// Determine the field to sum up
switch (di)
{
case MyEnums.DATA_IT EM.FIRST:
return adder (mdc.MYDATA, FIELD a); --> ????

case MyEnums.DATA_IT EM.SECOND:
return adder (mdc.MYDATA, FIELD b); --> ????
}
}

Basically, I want to get the field to add up, and pass this information
to the private "adder" function, along with the
proper field to use - I'd like to avoid summing up the items in a
switch() statement because each data array is quite large.

Any ideas on how to properly implement this?

Thanks!
Nov 16 '05 #1
2 6770
Hi! I edited your code to fit it in a smaller space for easier viewing,
but it shouldn't change the concepts.

Shmuel Cohen wrote:
public class MyEnums {
public enum DATA_ITEM {FIRST,SECOND,T HIRD,FOURTH,FIF TH};
}

public class TheData { public double a, b, c; }

public class Utility {
private static double adder (TheData data, FIELD fld) {
double val = 0.0;
val += data.fld;
}
public static double SUM_DATA (TheData mdc, MyEnums.DATA_IT EM di) {
switch (di) {
case MyEnums.DATA_IT EM.FIRST:
return adder (mdc, FIELD a);
case MyEnums.DATA_IT EM.SECOND:
return adder (mdc, FIELD b);
}
return 0.0;
}
}


The simplest way to accomplish this is to use reflection. Given a string
name, you can retrieve the field with that name and type FieldType from
object obj with the following expression:

(FieldType)obj. GetType().GetFi eld(name).GetVa lue(obj)

Here it is in your example:

public class Utility {
private static double adder (TheData data, string fld) {
double val = 0.0;
val += (double)data.Ge tType().GetFiel d(fld).GetValue (data);
return val;
}
public static double SUM_DATA(TheDat a mdc, MyEnums.DATA_IT EM di) {
switch (di) {
case MyEnums.DATA_IT EM.FIRST:
return adder (mdc, "a");
case MyEnums.DATA_IT EM.SECOND:
return adder (mdc, "b");
}
return 0.0;
}
}

If you find the syntax annoyingly verbose, you may find the following
class I whipped up helpful:

public class FieldReflector
{
private Object _obj;

public FieldReflector( Object obj)
{
_obj = obj;
}

public Object this[string name]
{
get
{
return _obj.GetType(). GetField(name). GetValue(_obj);
}
set
{
_obj.GetType(). GetField(name). SetValue(_obj, value);
}
}
}

Now you can simply do this:

private static double adder (TheData data, string fld)
{
FieldReflector datafr = new FieldReflector( data);
double val = 0.0;
val += (double)datafr[fld];
return val;
}

However, reflection can have a significant performance cost, so be
careful not to use it extensively in performance-critical paths.
Instead, you may wish to simply use an array of instance variables and
access them using properties:

public class TheData
{
public double[] fields = new double[3];
public double a
{
get { return fields[0]; }
set { fields[0] = value; }
}
public double b
{
get { return fields[1]; }
set { fields[1] = value; }
}
public double c
{
get { return fields[2]; }
set { fields[2] = value; }
}
public enum FieldNames { A, B, C }
}

public class Utility
{
private static double adder (TheData data, TheData.FieldNa mes fld)
{
double val = 0.0;
val += (double)data.fi elds[(int)fld];
return val;
}
}

Please ask if any of this is unclear to you. I hope this helps.
--
Derrick Coetzee, Microsoft Speech Server developer
This posting is provided "AS IS" with no warranties, and confers no
rights. Use of included code samples are subject to the terms
specified at http://www.microsoft.com/info/cpyright.htm
Nov 16 '05 #2
Derrick,

Awesome! Great explanation - just what I was looking for - thanks a
million!
"Derrick Coetzee [MSFT]" <dc******@onlin e.microsoft.com > wrote in message
news:41******** ******@online.m icrosoft.com...
Hi! I edited your code to fit it in a smaller space for easier viewing,
but it shouldn't change the concepts.

Shmuel Cohen wrote:
public class MyEnums {
public enum DATA_ITEM {FIRST,SECOND,T HIRD,FOURTH,FIF TH};
}

public class TheData { public double a, b, c; }

public class Utility {
private static double adder (TheData data, FIELD fld) {
double val = 0.0;
val += data.fld;
}
public static double SUM_DATA (TheData mdc, MyEnums.DATA_IT EM di) {
switch (di) {
case MyEnums.DATA_IT EM.FIRST:
return adder (mdc, FIELD a);
case MyEnums.DATA_IT EM.SECOND:
return adder (mdc, FIELD b);
}
return 0.0;
}
}


The simplest way to accomplish this is to use reflection. Given a string
name, you can retrieve the field with that name and type FieldType from
object obj with the following expression:

(FieldType)obj. GetType().GetFi eld(name).GetVa lue(obj)

Here it is in your example:

public class Utility {
private static double adder (TheData data, string fld) {
double val = 0.0;
val += (double)data.Ge tType().GetFiel d(fld).GetValue (data);
return val;
}
public static double SUM_DATA(TheDat a mdc, MyEnums.DATA_IT EM di) {
switch (di) {
case MyEnums.DATA_IT EM.FIRST:
return adder (mdc, "a");
case MyEnums.DATA_IT EM.SECOND:
return adder (mdc, "b");
}
return 0.0;
}
}

If you find the syntax annoyingly verbose, you may find the following
class I whipped up helpful:

public class FieldReflector
{
private Object _obj;

public FieldReflector( Object obj)
{
_obj = obj;
}

public Object this[string name]
{
get
{
return _obj.GetType(). GetField(name). GetValue(_obj);
}
set
{
_obj.GetType(). GetField(name). SetValue(_obj, value);
}
}
}

Now you can simply do this:

private static double adder (TheData data, string fld)
{
FieldReflector datafr = new FieldReflector( data);
double val = 0.0;
val += (double)datafr[fld];
return val;
}

However, reflection can have a significant performance cost, so be careful
not to use it extensively in performance-critical paths. Instead, you may
wish to simply use an array of instance variables and access them using
properties:

public class TheData
{
public double[] fields = new double[3];
public double a
{
get { return fields[0]; }
set { fields[0] = value; }
}
public double b
{
get { return fields[1]; }
set { fields[1] = value; }
}
public double c
{
get { return fields[2]; }
set { fields[2] = value; }
}
public enum FieldNames { A, B, C }
}

public class Utility
{
private static double adder (TheData data, TheData.FieldNa mes fld)
{
double val = 0.0;
val += (double)data.fi elds[(int)fld];
return val;
}
}

Please ask if any of this is unclear to you. I hope this helps.
--
Derrick Coetzee, Microsoft Speech Server developer
This posting is provided "AS IS" with no warranties, and confers no
rights. Use of included code samples are subject to the terms
specified at http://www.microsoft.com/info/cpyright.htm

Nov 16 '05 #3

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

Similar topics

1
2626
by: Mike Malter | last post by:
I am just starting to work with reflection and I want to create a log that saves relevant information if a method call fails so I can call that method again later using reflection. I am experimenting a bit with what I need to do this and have the following code snippet. But first if I pass the assembly name and type to Activator.CreateInstance() it always fails. However if I walk my assembly and get a type value, the call to...
7
6376
by: maf | last post by:
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(FieldInfo fi in fieldInfos ) { Console.WriteLine("Name: {0}" fi.Name); Console.WriteLine("Value: {0} " fi.GetValue(null).ToString());
8
2549
by: Eyeawanda Pondicherry | last post by:
I have put some code together that creates an enum dynamically from some database values. The enum can be read perfectly by an application that references the dynamically generated dll. If I /emit/ a new version of the assembly, and start the application again, the new values will appear for the enum. However, suppose I want the application to remain in a running state.
3
17070
by: System.Reflection Activator | last post by:
************************************** //Load the Assembly Assembly a = Assembly.LoadFrom(sAssembly); //Get Types so we can Identify the Interface. Type mytypes = a.GetTypes(); BindingFlags flags = (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly); //Iterate through the Assembly to find Class with a Public Interface.
4
1135
by: Phill. W | last post by:
Does anyone happen to have a snippet of code that, for a given Type, produces a list of the properties, methods, constructors, and so on for that Class? TIA, Phill W.
15
2159
by: Jeff Mason | last post by:
Hi, I'm having a reflection brain fog here, perhaps someone can set me on the right track. I'd like to define a custom attribute to be used in a class hierarchy. What I want to do is to have an attribute which can be applied to a class definition of a class which inherits from a base, mustinherit class. I want to define methods in the base class which will access the contents of the attribute as it is applied to
3
319
by: George | last post by:
Hello, I am building an assembly that connects to a third party application via http. I need create a http message that I post to the third party application. The message is very complicated with alot of business rules which I can define in a xml/config file. So, I will need to parse the xml file and also use reflection to retrieve certain data from my business objects via properties. This assembly will be used alot so performance is...
11
6409
by: =?Utf-8?B?dG9iaXdhbl9rZW5vYmk=?= | last post by:
The following code is in a custom deserializer: object value = (int) 1; string nameToParse = Enum.GetName(field.FieldType, value); value = Enum.Parse(field.FieldType, nameToParse); Currently we follow the path below: intValue --enum name --enum value
34
1935
by: mdh | last post by:
Hi All, Just when I thought things were going to get easy! Structs. I **thought** I had copied the examples pretty closely, but am getting a number of errors. The code:
0
9646
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9484
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10157
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10097
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9957
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6742
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5386
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5518
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2887
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.