473,395 Members | 1,437 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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,FIFTH};
...
}

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_ITEM di)
{

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

case MyEnums.DATA_ITEM.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 6743
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,THIRD,FOURTH,FIFTH};
}

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_ITEM di) {
switch (di) {
case MyEnums.DATA_ITEM.FIRST:
return adder (mdc, FIELD a);
case MyEnums.DATA_ITEM.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().GetField(name).GetValue(o bj)

Here it is in your example:

public class Utility {
private static double adder (TheData data, string fld) {
double val = 0.0;
val += (double)data.GetType().GetField(fld).GetValue(data );
return val;
}
public static double SUM_DATA(TheData mdc, MyEnums.DATA_ITEM di) {
switch (di) {
case MyEnums.DATA_ITEM.FIRST:
return adder (mdc, "a");
case MyEnums.DATA_ITEM.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.FieldNames fld)
{
double val = 0.0;
val += (double)data.fields[(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******@online.microsoft.com> wrote in message
news:41**************@online.microsoft.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,THIRD,FOURTH,FIFTH};
}

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_ITEM di) {
switch (di) {
case MyEnums.DATA_ITEM.FIRST:
return adder (mdc, FIELD a);
case MyEnums.DATA_ITEM.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().GetField(name).GetValue(o bj)

Here it is in your example:

public class Utility {
private static double adder (TheData data, string fld) {
double val = 0.0;
val += (double)data.GetType().GetField(fld).GetValue(data );
return val;
}
public static double SUM_DATA(TheData mdc, MyEnums.DATA_ITEM di) {
switch (di) {
case MyEnums.DATA_ITEM.FIRST:
return adder (mdc, "a");
case MyEnums.DATA_ITEM.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.FieldNames fld)
{
double val = 0.0;
val += (double)data.fields[(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
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...
7
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...
8
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...
3
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...
4
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
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...
3
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...
11
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...
34
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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...

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.