Solved

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

Posted on 2010-09-15
20
965 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

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
 

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

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

630 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