Solved

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

Posted on 2010-09-15
20
936 Views
Last Modified: 2012-06-27
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
0
Comment
Question by:SSschultz
20 Comments
 
LVL 10

Expert Comment

by:james-ct16
ID: 33688699
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
 

Author Comment

by:SSschultz
ID: 33688709
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
 
LVL 10

Expert Comment

by:james-ct16
ID: 33688723
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
 

Author Comment

by:SSschultz
ID: 33688746
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
 

Author Comment

by:SSschultz
ID: 33688751
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
 
LVL 10

Expert Comment

by:james-ct16
ID: 33688752
Can you provide an example of how these numbers and string are being generated / retrieved?
0
 
LVL 10

Expert Comment

by:james-ct16
ID: 33688757
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
 

Author Comment

by:SSschultz
ID: 33688758
do I simply need to add "number" as a text string to the stringname and then use your first response?
0
 
LVL 10

Expert Comment

by:james-ct16
ID: 33688761
That should simply do it.
0
 

Author Comment

by:SSschultz
ID: 33688781
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:SSschultz
ID: 33688791
let me try added the "number" to the stringname. sorry it's late.
0
 
LVL 10

Accepted Solution

by:
james-ct16 earned 250 total points
ID: 33688836
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
 

Author Comment

by:SSschultz
ID: 33688933
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
 
LVL 10

Expert Comment

by:james-ct16
ID: 33689075
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
 
LVL 7

Assisted Solution

by:gsiric
gsiric earned 250 total points
ID: 33689256
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
 
LVL 10

Expert Comment

by:james-ct16
ID: 33689321
gsiric, i tend to agree if I were implementing this I think id be looking at a collection based solution.
0
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33690007
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
 

Author Comment

by:SSschultz
ID: 33699119
I'll be closing this today sometime when I get a chance to finish testing.
Thanks for everyones help and input.
0
 

Author Comment

by:SSschultz
ID: 33717130
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
 

Author Comment

by:SSschultz
ID: 33717972
Cancel close request. tried to award points and it didn't work.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Linq help 1 16
Need help with a query 6 55
Library to convert HTML to PDF. 8 44
Visual Studio 2013 debugging 2 19
Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video discusses moving either the default database or any database to a new volume.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now