[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Dynamic Variable Assignment in C#

Posted on 2006-07-11
12
Medium Priority
?
434 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 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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone 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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…
Suggested Courses
Course of the Month20 days, 13 hours left to enroll

865 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