Solved

Dynamic Variable Assignment in C#

Posted on 2006-07-11
12
408 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 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
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 

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

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!

Question has a verified solution.

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

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
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!
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…

695 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