C# reflection? assign value to static variable changed by reflection?

Hi,
Newbie question:

How do I assign value to a static variable that the static variable is part of a string within
a class and it changes frequently?

Need actual code example: I've looked at several online posts of examples and cannot figure it out.

Example:

public static int ABCnumber;
public static int ABDnumber;
public static int ABEnumber;
//and over 200 of this combinations.

in different class
String stringname =  (this changes frequently and could be over 200 different names)
(stringname would be ABC or ABD or ABE or other 200 names)
(the "number" part of static int would be constant and does not change, added as string?)
I want to assign an int to the public static int based on whatever the stringname is currently.
I think Reflection is how this is done but not sure?
Please list code example based on above and not online links.
Thanks
SSschultzAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
james-ct16Connect With a Mentor Commented:
Howdy

I would not be looking at reflection for performance, as a general rule reflection is significantly slowly direct access, you may be interested in this article http://www.west-wind.com/weblog/posts/351.aspx

James
0
 
james-ct16Commented:
Howdy

The following code example should be sufficient to extend what you are trying to do.

Hope that helps

James

        private void Form1_Load(object sender, EventArgs e)
        {
            FieldInfo fi = typeof(test1).GetField("abcNumber");
            fi.SetValue(null, 7);

            int value = (int)fi.GetValue(null);
            System.Diagnostics.Debug.WriteLine(value);
        }


    public static class test1
    {
        public static int abcNumber;
    }

Open in new window

0
 
SSschultzAuthor Commented:
Thanks James.

the number part of ABCnumber is constant but the ABC is what changes, don't I need a string to add to the ABC get field?
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
james-ct16Commented:
The value contained within that getfield could be any string you like so in your case you would just build the string.
eg

string fieldName = "abc123"
typeof(test1).GetField(fieldName);

It gets a little more complicated if its the class name that is going to change as well
0
 
SSschultzAuthor Commented:
The ABC is from a separate string and I need to add "number" to it and then
assign a value to the public static int.
Tricky part is that ABC could be 200 different names all with the text "number" after them as this is the
name of the public static int (ABCnumber).


0
 
SSschultzAuthor Commented:
Currently I have if statements hard coded to exact match if ABCnumber = .... but to use this same thing for over 200 or more... ughhhh
0
 
james-ct16Commented:
Can you provide an example of how these numbers and string are being generated / retrieved?
0
 
james-ct16Commented:
Can you also provide an outline of what you are trying to achieve because this sounds horribly messy i suspect there are a lot neater ways to solve your problem.
0
 
SSschultzAuthor Commented:
do I simply need to add "number" as a text string to the stringname and then use your first response?
0
 
james-ct16Commented:
That should simply do it.
0
 
SSschultzAuthor Commented:
It sounds very messy and inefficient but I think it may be fastest?

It's realtime streaming app. where the stringname changes rapidly.
I have public static int   ABCnumber for example.
as it receives and reads the stringname (ABC) in this case, it takes an int also read at same time as stringname.
This int is what I want to assign to the public static int ABCnumber (again the ABC is changing all the time).
I have to hardcode the public static int ABCnumber, ABDnumber etc.
Currently I"m using if statements  (if stringname = ABC) .... assign public static int ABCnumber etc.
Which is fine for 10, and it works.
But I would like to use faster approach and easier to maintain by changing it with a string etc plus the way the data is, I have to have a copy of each if statement one after the other (over 200 of them x 200 if I procede with my current if statements.
hopefully that's not more confusing.
0
 
SSschultzAuthor Commented:
let me try added the "number" to the stringname. sorry it's late.
0
 
SSschultzAuthor Commented:
James,
Great article, found it helpful with speed question.

Still trying to get your reflection example to work.
what does the fi.Setvalue(null,7) do?
and the int value = (int)fi.GetValue(null) do?
I'm trying to get ABCnumber in place of the "value".
Was able to get the number added to back of string.
0
 
james-ct16Commented:
so

fi.SetValue(null,7)
this sets the static field abcnumber on static class test1 to the value 7 usually where there is the null parameter you would pass your object instance but its ignored when dealing with statics

fi.GetValue(null)
this gets the value from the static field abcnumber on static class test1. this should of course return 7.

FieldInfo fi = typeof(test1).GetField("abcNumber");
this is the line which sets up our reflection, so it says i want to work with type test1 (thats the static class in the example) getfield searches the class for the public static field "abcNumber" please remember when dealing with reflection its case sensitive.
0
 
gsiricConnect With a Mentor Commented:
Maybe you should use C# Dictionary class for this ?
Here is example :


using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static Dictionary<string, int> example = new Dictionary<string, int>();
        static void AddPair(string s, int i)
        {
            example.Add(s+i.ToString(),i);
        }

        static bool TryGetValue(string s, int i, out int val)
        {
            if (example.TryGetValue(s + i.ToString(), out val))
            {
                return true;
            }

            return false;
        }

        static bool ContainsPair(string s, int i)
        {
            return example.ContainsKey(s + i.ToString());
        }

        static void Main(string[] args)
        {
            // A. Create a new Dictionary with two keys and two values.
            

            AddPair("ABD",1);
            AddPair("ABD",2);
            AddPair("BDA",2);


            // B. Lookup a string in the Dictionary.
            int value;
            if (TryGetValue("ABD",2, out value))
            {
                Console.WriteLine("Found ABD2 {0}", value);
            }

            // C. See if it contains this key.
            Console.WriteLine("Contain BDA2 ? = " + ContainsPair("BDA",2));
            Console.WriteLine("Contain BDA3 ? = " + ContainsPair("BDA", 3));

            // D. Add this key if it isn't there.
            if (!ContainsPair("ACD",2))
            {
                AddPair("ACD", 2);
            }

            // E. Enumerate the keys
            foreach (KeyValuePair<string, int> pair in example)
            {
                Console.WriteLine("Key = {0}, Value = {1}", pair.Key, pair.Value);
            }

            Console.ReadKey();
        }
    }
}

Open in new window

0
 
james-ct16Commented:
gsiric, i tend to agree if I were implementing this I think id be looking at a collection based solution.
0
 
Gururaj BadamCommented:
SSschultz,

I think this is how it should be done.
        private bool SetPropertyValue(string _propertyPrefix, int _intValue)
        {
            PropertyInfo pi = typeof(DialogBox1).GetProperty(_propertyPrefix + "number", System.Reflection.BindingFlags.Static);
            if (pi != null)
            {
                pi.SetValue(null, _intValue, null);
                return true;
            }

            return false;
        }

Open in new window

0
 
SSschultzAuthor Commented:
I'll be closing this today sometime when I get a chance to finish testing.
Thanks for everyones help and input.
0
 
SSschultzAuthor Commented:
How do I replace records in the dictionary?
Do I just keep adding and it will replace the previous value?

Seem to have an issue with trying to add another value for same key after it has been added previously.

Thanks.
0
 
SSschultzAuthor Commented:
Cancel close request. tried to award points and it didn't work.
0
All Courses

From novice to tech pro — start learning today.