?
Solved

Dynamic Variable Assignment in C#

Posted on 2006-07-11
12
Medium Priority
?
415 Views
Last Modified: 2008-03-10
I am reading settings from a XML file:
<settings>
<setting1>value1</setting1>
<setting2>value2</setting2>
</settings>

What I want is to read the XML file and crete dinamically variables with the XML element name.

In the end I should have a variable called "setting1" with value "value1", another variable called "setting2" with value "value2". If I execute Console.WriteLine(setting2) it should output "value1".

Is there a way to do this?

Thanks
0
Comment
Question by:hugoduraes
[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
12 Comments
 
LVL 48

Accepted Solution

by:
AlexFM earned 1500 total points
ID: 17082270
This looks like task for reflection, but .NET reflection support is restricted, program cannot modify itself on the fly, as it was possible, for example, with FoxPro macros. I suggest you to use arrays, for example:
string settings[] = new string[100];

// fill array reading XML file.

If you don't know number of settings, use ArrayList or List<T>:
List<string> list = new list<string>();

// fill list reading XML file.

If you don't know names of variables and want to keep dynamic structure which contains element name with values, use HashTable or Dictionary< > class:

Dictionary< string, list<string> > dictionary = new Dictionary< string, list<string> >();

Use variable name as dictionary key, and list of values as dictionary value.
0
 
LVL 22

Expert Comment

by:cookre
ID: 17082464
AlexFM is spot on with hash table.
0
 
LVL 13

Expert Comment

by:devsolns
ID: 17083103
It sounds like what you want already exists.  In 2.0 when you add elements to the *.settings file it dynamically allows you to access your settings through properties.  so,

If I add two values to my settings file.  BTW, they are type safe.

<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="JUNK__ConsoleApplication1.Properties" GeneratedClassName="Settings">
  <Profiles />
  <Settings>
    <Setting Name="MyName" Type="System.String" Scope="User">
      <Value Profile="(Default)">gary</Value>
    </Setting>
    <Setting Name="MyBirthday" Type="System.DateTime" Scope="User">
      <Value Profile="(Default)">1982-02-01</Value>
    </Setting>
  </Settings>
</SettingsFile>


I can immediatly access them in code like this,

                string name = Properties.Settings.Default.MyName;
                DateTime birthDay = Properties.Settings.Default.MyBirthday;


The underlying code gened looks like,,




    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
       
        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
       
        public static Settings Default {
            get {
                return defaultInstance;
            }
        }
       
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("gary")]
        public string MyName {
            get {
                return ((string)(this["MyName"]));
            }
            set {
                this["MyName"] = value;
            }
        }
       
        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("1982-02-01")]
        public global::System.DateTime MyBirthday {
            get {
                return ((global::System.DateTime)(this["MyBirthday"]));
            }
            set {
                this["MyBirthday"] = value;
            }
        }
    }


gp
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:hugoduraes
ID: 17083218
devsolns: And how can I create or add elements to the *.settings file?
0
 
LVL 13

Expert Comment

by:devsolns
ID: 17083276
If a settings file does not already exist in your project then add new item->settings file.  When you double click it will open up a grid for easy entry of items.  You can also choose to open it in normal xml view if you'd like.
0
 
LVL 13

Expert Comment

by:devsolns
ID: 17083305
You didnt specify a requirment to generate this at runtime.  To generate a class at runtime is certainly possible using either Codedom or EMIT but may add a lot of complexity where there shouldnt be.
0
 

Author Comment

by:hugoduraes
ID: 17083357
Ok... I'm beggining to like this solution! ;)

Just one more question... can I change settings value? I have to allow users to change these settings values...
0
 
LVL 13

Expert Comment

by:devsolns
ID: 17083780
If you change the "value" then you will need to recompile! Yeah that is probably the biggest limitation.

0
 

Author Comment

by:hugoduraes
ID: 17088759
I'll have to stick with hashtables then...

Thanks ;)
0
 
LVL 13

Expert Comment

by:devsolns
ID: 17090641
dont agree, next step was ConfigurationManager which is better than hash table but o'well.
0
 

Author Comment

by:hugoduraes
ID: 17090743
With ConfigurationManager can I change configuration values during runtime? Or do I need to recompile?
0
 
LVL 13

Expert Comment

by:devsolns
ID: 17091708
You can change them at runtime.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
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…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
Suggested Courses

777 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