Solved

In C# how to name variables dynamically

Posted on 2012-03-20
4
296 Views
Last Modified: 2012-03-23
]I need to create an a variable set to an object dynamically using the code below.  There can be anywhere from 0 to many so I need to set lr with a numeric value for example lr1, lr2 etc... I am realizing what I have below cannot be done with a simple concatination.  

 [embed=snippet 8250291
         foreach (int i in labreports)
            {
                MHLServices.FaxQueueRequestILabReport "lr" + i.ToString() = new MHLServices.FaxQueueRequestILabReport();
                lr + i.lr_uid = labreports.items[i];
                fax.FaxQueueRequestILabReports.Add(lr + i);
            }

Open in new window

0
Comment
Question by:monica73174
  • 2
4 Comments
 
LVL 39

Accepted Solution

by:
Kyle Abrahams earned 500 total points
ID: 37744105
You don't.   Create a List and refer to it by index.

Why not just add it directly:




foreach (int i in labreports)
{
   fax.FaxQueueRequestILabReports.Add(labreports.items[ i ]);
}
0
 

Author Comment

by:monica73174
ID: 37744113
I just have no idea how many I  need to create.
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 37744142
Lists are dynamic.  You create as many as you need.

http://dotnetanalysis.blogspot.com/2011/04/list.html
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 37744242
Use a Dictionary:
http://msdn.microsoft.com/en-us/library/xfhwa508(VS.85).aspx

The variable name will be the key.
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

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
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…
This video discusses moving either the default database or any database to a new volume.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

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

15 Experts available now in Live!

Get 1:1 Help Now