Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to dynamically generate name of constant

Status
Not open for further replies.

ecrefin

Programmer
Sep 3, 2003
2
US
Hi All,

I'm new to C#, but I'm pretty sure I've seen this done in Java so I'm sure it can be done here. What I would like to do is dyanmically generate the name of the constant I would like to read. Here is an example of what I want to do.

In a separate file for constants (ConstantsFile.cs):
public static String CODE_A = "1;
public static String CODE_B = "2;

In another file, in some method, refer to these constants "dynamically" (I don't know what to call it):
String sCodeValue="A"; // This value would be unknown
// but is given here to clarify
String sConstantValue=ConstantsFile.CODE_(+sCodeValue)
// I want to pull the value of ConstantsFile.CODE_A,
// so in this case, sConstantValue would be set to "1"

So, it's the last line that I really don't know how to write. I would like the constant name to be appended with the code value which has come in. If that can't be done in that way, it's also fine for me to do something like:
String sCodeValue="A";
sCodeValue="CODE_"+sCodeValue;
String sConstantValue=ConstantFile.(sCodeValue)

I just can't figure out how to do it. This can be done, right? Am I seeking something that has a much more complex solution?

Thanks in advance,
Liz
 
It can be done, but it's not fast, nor is it easy. You would have to use reflection (see System.Reflection namespace) to read through your assembly, looking for something that looks like "CODE_" + sCodeName. If you find it, reflection can then give you the value.

Did I mention it wasn't easy? Or that it wasn't fast? It's ugly, too.

I would look at doing it a different way - perhaps a static array with an enum you can use to index into it (assuming the value of your lookup is a string).

If your value is an integer, you can get it from an enum directly.

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
Thanks, Chip --

Ah, reflection... I had forgotten all about that. I never used it in Java, but I had a general understanding of it. I might play around with it if I have a chance, if only to get myself more familiar with how it works. I ended up using a hashtable for my values and everything works just fine. I was attracted to this solution, though, because it seemed like it would be elegant. From what you have explained, however, perhaps it's not as elegant a solution as I thought it would be.

Thanks again!

Liz
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top