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
Solved

Dynamic Variable Assignment in C#

Posted on 2006-07-11
12
395 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
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 

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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
List<PaisEntity> - show some 1 28
Call Controller Action Method from ASPX 2 22
C# LINQ ForEach() question 6 48
MailAddress in vb 4 29
Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

790 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