Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How do I reference an object using the object name passed in a string.

Posted on 2015-02-10
9
Medium Priority
?
149 Views
Last Modified: 2015-02-15
Hello,
I thought I had this sorted via a question I posed two weeks ago - but unfortunately I didn't. Below is just a mock up to demonstrate what I am trying to achieve. I want the user to be able to pass in the name of an object in a text array(eg. "MyDict", "MyClass" etc..) and for the application to be able to add the named object to an array of objects.  In the highlighted code below the 1st line moves "Dict" to the object array varList. I want it to add the obj Dict just like the line below does. Any idea how I can achieve this ? Please give working example if possible

regards
Pat


namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
        Dictionary<string, string> dict = new Dictionary<string, string>() {{"cat", "manx"},{"dog", "labrador"}};
        List<object> varList=new List<object>();
        string[] delimitedList= new string[] {"obj1","obj2","dict"};

        for (int j = 0; j < 3; j++)
        {
            switch (delimitedList[j])
            {
               case "dict":
                    varList.Add(delimitedList[j].Replace("\"", ""));  //I would like this to work just like the line below//
                    varList.Add(dict);
                    break;
               case "obj1":
                    varList.Add(delimitedList[j].Replace("\"", ""));
                    break;

                default:
                    break;
            }
          }
         }
        }
    }
0
Comment
Question by:pclarke7
[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
  • 4
  • 4
9 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40601954
I want the user to be able to pass in the name of an object in a text array...
Is this object pointed to by a variable that has the same name as the string being passed in by the user?
0
 
LVL 23

Accepted Solution

by:
Michael Fowler earned 2000 total points
ID: 40602041
One way would be to have a dictionary of string names and objects eg

Dictionary<string, Dictionary> myDicts = new Dictionary();
Dictionary<string, string> dict = new Dictionary<string, string>() {{"cat", "manx"},{"dog", "labrador"}};
myDicts.Add("dict", dict);

Open in new window


You can then easily look up the corresponding object based on a string value
0
 

Author Comment

by:pclarke7
ID: 40602664
Hi Kaufmed,
yes, the variable name will have the same name as the object and I want the variable name to point to the object. So variables ("MyCar","MyCar.colour","MyDict") will point to obJect MyCar object, MyCar.colour object property and MyDict dictionary object respectively.

Hi Michael
Yes , I believe that this will work. However what is the overhead ? Is the "dict",dict dictionary entry a pointer to dict or does it contain the dict object. If it contains the object then this would be excessive

regards
Pat
0
Fill in the form and get your FREE NFR key NOW!

Veeam® is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

 
LVL 23

Expert Comment

by:Michael Fowler
ID: 40602708
Objects are reference types and so pointers are stored
0
 

Author Comment

by:pclarke7
ID: 40604353
Hi Michael,
I have been looking at your suggestion.  I will work well for objects such as lists and dictionaries , but not so well for class objects.  For instance if I have a Class with 50 properties Myclass.colour, Myclass.size,, Myclass.shape etc.... and if I want to allow the user to point to a property by name then I would need to set up each property in the dictionary which is a lot of effort.

Is there any other way, using reflection, to point variable  "MyClass.colour" to object property Myclass.colour ?

regards
Pat
0
 
LVL 23

Expert Comment

by:Michael Fowler
ID: 40604379
Yes, use the Type.GetProperty and the PropertyInfo.GetValue methods
https://msdn.microsoft.com/en-us/library/kz0a8sxy(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/hh194385(v=vs.110).aspx

for example

myClass.GetType().GetProperty("colour").GetValue(myClass, null);

Open in new window

0
 

Author Comment

by:pclarke7
ID: 40604567
Hi Michael
so could I do something like this

string[] delimitedList= new string[] {"MyClass.colour", "Myclass.size"}; // user has requested these two values at runtime
for(j=0,j<delimitedList.Lenth;j++)
{
// Substring  "MyClass.colour" into two variables called class & prop (class="MyClass" & prop="colour")

myDicts.Add(delimitedList[j] , myClass.GetType().GetProperty(class).GetValue(prop, null););

}
0
 
LVL 23

Expert Comment

by:Michael Fowler
ID: 40604666
This is getting confusing.

A class is a reference type and so when you create a new class object eg
Dog myDog = new Dog("German Shepherd", "Black", "2");

Open in new window

myDog is a pointer to this instance of the Dog class. To access the information stored in this class the application needs to know where to look and the reference myDog contains this memory location.

In my example above reflection is using a string value to find a variable in a given instance of a class where the variable name matches the string. Reflection cannot locate a class in this way as the class does not know it has a pointer to it named myDog.

Given this you will always need to store pointers to the class objects if you wish to retrieve information from these classes at a later date, in fact once a class goes out of scope the garbage collector will remove it.

So in answer to your question, no it will not work.

What are you trying to achieve here? It would help me to provide alternatives if I understood your goals and application type (winform, web site etc).
0
 

Author Comment

by:pclarke7
ID: 40611218
Hi Michael,
thanks for all your input. I have successfully used a dictionary to allow user to select either an object or object property. I get the property information using PropertyInfo.

regards
Pat
0

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

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 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…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

715 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