Solved

Dynamic Variable Assignment in C#

Posted on 2006-07-11
12
378 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
12 Comments
 
LVL 48

Accepted Solution

by:
AlexFM earned 500 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
 

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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

705 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

22 Experts available now in Live!

Get 1:1 Help Now