Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Get an object value using a string

Get an object value using a string

Scheduled Pinned Locked Moved C#
7 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    MrEyes
    wrote on last edited by
    #1

    Hello all, Odd title, not an easy one to summarise. Basically I am trying to find a way of access an object value from a string that contains that objects name. So, lets assume I have the following basic class

    class NoddyClass
    {
    public string foo;
    public string bar;
    }

    Which is used by the following

    class NoddyProcess
    {
    private NoddyClass nc;

    public NoddyProcess()
    {
    this.nc = new NoddyClass()
    this.nc.foo = "thingys";
    this.nc.bar = "doodars";
    }

    public void GetValueFromString(string value)
    {
    //A miracle occurs here
    }
    }

    class AnotherNoddyProcess
    {
    private void DoSomething()
    {
    NoddyProcess np = new NoddyProcess();
    np.GetValueFromString("foo");
    }
    }

    So putting all this together in the GetValueFromString method I need to access this.nc and using the passed string retrieve the value of this.nc.foo and return it to the caller. I am assuming that this can be done with reflection, however I seem to have hit a wall on this and could do with a prod in the right direction. P.S. I realise that in the examples given above none of this is actually necessary, however these are extemely simplfied versions of a much more complex framework.

    T L K 3 Replies Last reply
    0
    • M MrEyes

      Hello all, Odd title, not an easy one to summarise. Basically I am trying to find a way of access an object value from a string that contains that objects name. So, lets assume I have the following basic class

      class NoddyClass
      {
      public string foo;
      public string bar;
      }

      Which is used by the following

      class NoddyProcess
      {
      private NoddyClass nc;

      public NoddyProcess()
      {
      this.nc = new NoddyClass()
      this.nc.foo = "thingys";
      this.nc.bar = "doodars";
      }

      public void GetValueFromString(string value)
      {
      //A miracle occurs here
      }
      }

      class AnotherNoddyProcess
      {
      private void DoSomething()
      {
      NoddyProcess np = new NoddyProcess();
      np.GetValueFromString("foo");
      }
      }

      So putting all this together in the GetValueFromString method I need to access this.nc and using the passed string retrieve the value of this.nc.foo and return it to the caller. I am assuming that this can be done with reflection, however I seem to have hit a wall on this and could do with a prod in the right direction. P.S. I realise that in the examples given above none of this is actually necessary, however these are extemely simplfied versions of a much more complex framework.

      T Offline
      T Offline
      TJoe
      wrote on last edited by
      #2

      Since you are accessing fields, check out this[^]. It has an example that should get you started. For properties, check out this[^].

      Take care, Tom ----------------------------------------------- Check out my blog at http://tjoe.wordpress.com

      1 Reply Last reply
      0
      • M MrEyes

        Hello all, Odd title, not an easy one to summarise. Basically I am trying to find a way of access an object value from a string that contains that objects name. So, lets assume I have the following basic class

        class NoddyClass
        {
        public string foo;
        public string bar;
        }

        Which is used by the following

        class NoddyProcess
        {
        private NoddyClass nc;

        public NoddyProcess()
        {
        this.nc = new NoddyClass()
        this.nc.foo = "thingys";
        this.nc.bar = "doodars";
        }

        public void GetValueFromString(string value)
        {
        //A miracle occurs here
        }
        }

        class AnotherNoddyProcess
        {
        private void DoSomething()
        {
        NoddyProcess np = new NoddyProcess();
        np.GetValueFromString("foo");
        }
        }

        So putting all this together in the GetValueFromString method I need to access this.nc and using the passed string retrieve the value of this.nc.foo and return it to the caller. I am assuming that this can be done with reflection, however I seem to have hit a wall on this and could do with a prod in the right direction. P.S. I realise that in the examples given above none of this is actually necessary, however these are extemely simplfied versions of a much more complex framework.

        L Offline
        L Offline
        led mike
        wrote on last edited by
        #3

        MrEyes wrote:

        however these are extemely simplfied versions of a much more complex framework.

        This "much more complex framework" is what? Or is it what you are developing?

        M 1 Reply Last reply
        0
        • L led mike

          MrEyes wrote:

          however these are extemely simplfied versions of a much more complex framework.

          This "much more complex framework" is what? Or is it what you are developing?

          M Offline
          M Offline
          MrEyes
          wrote on last edited by
          #4

          Basically I have a library that has an encrypted XML file sat underneath it, when the library object is created it reads in, decrypts and deserialises the XML to an class level object. This object is then used within the library to drive various things. This library exposes a COM interface to allow none .NET applications to interact with it, and until today these external applications did not require the ability to directly extract data from the XML file. Today however, this functionality is now a requirement. The XML itself while structurally simple, contains alot of elements. In fact it looks something like this:

          <Data>
          <Element1></Element1>
          <Element2></Element2>
          ....
          ....
          <Element1000></Element1000>
          </Data>

          Due to the volume of elements it isnt really feasible to create an externally accessible property for every single one, i.e:

          public string GetElement1Value
          {
          return this.myXmlObject.Element1
          }

          There was also the option of not using the current XML object in memory, re-reading, re-decrypting it, and then using XmlDocument and Xpath to get the value, however I belive the overhead here would be greater than using reflection. So this is where the idea of using reflection comes in. In fact since posting I have found a solution, so this is what I am currently trying out:

          public string GetConfigurationValue(string key)
          {
          Type itemType = typeof(MyXmlObject);

          PropertyInfo property = itemType.GetProperty(key);
          
          if (property == null)
          {
              throw new ArgumentException("Invalid XML element key", key);
          }
          
          return property.GetValue(this.myXmlObject, null).ToString();
          

          }

          Which as you can see is alot shorter than using 1000+ property accessor/methods. Maybe I am barking up the wrong tree here, so feel free to point out something that I have considered as I have to admit using reflection doesnt sit very well with me.

          L P 2 Replies Last reply
          0
          • M MrEyes

            Basically I have a library that has an encrypted XML file sat underneath it, when the library object is created it reads in, decrypts and deserialises the XML to an class level object. This object is then used within the library to drive various things. This library exposes a COM interface to allow none .NET applications to interact with it, and until today these external applications did not require the ability to directly extract data from the XML file. Today however, this functionality is now a requirement. The XML itself while structurally simple, contains alot of elements. In fact it looks something like this:

            <Data>
            <Element1></Element1>
            <Element2></Element2>
            ....
            ....
            <Element1000></Element1000>
            </Data>

            Due to the volume of elements it isnt really feasible to create an externally accessible property for every single one, i.e:

            public string GetElement1Value
            {
            return this.myXmlObject.Element1
            }

            There was also the option of not using the current XML object in memory, re-reading, re-decrypting it, and then using XmlDocument and Xpath to get the value, however I belive the overhead here would be greater than using reflection. So this is where the idea of using reflection comes in. In fact since posting I have found a solution, so this is what I am currently trying out:

            public string GetConfigurationValue(string key)
            {
            Type itemType = typeof(MyXmlObject);

            PropertyInfo property = itemType.GetProperty(key);
            
            if (property == null)
            {
                throw new ArgumentException("Invalid XML element key", key);
            }
            
            return property.GetValue(this.myXmlObject, null).ToString();
            

            }

            Which as you can see is alot shorter than using 1000+ property accessor/methods. Maybe I am barking up the wrong tree here, so feel free to point out something that I have considered as I have to admit using reflection doesnt sit very well with me.

            L Offline
            L Offline
            led mike
            wrote on last edited by
            #5

            MrEyes wrote:

            In fact it looks something like this:

            WOW... I am sorry but using XML in that way crosses my threshold of acceptability. I am afraid I cannot assist you any further.

            1 Reply Last reply
            0
            • M MrEyes

              Hello all, Odd title, not an easy one to summarise. Basically I am trying to find a way of access an object value from a string that contains that objects name. So, lets assume I have the following basic class

              class NoddyClass
              {
              public string foo;
              public string bar;
              }

              Which is used by the following

              class NoddyProcess
              {
              private NoddyClass nc;

              public NoddyProcess()
              {
              this.nc = new NoddyClass()
              this.nc.foo = "thingys";
              this.nc.bar = "doodars";
              }

              public void GetValueFromString(string value)
              {
              //A miracle occurs here
              }
              }

              class AnotherNoddyProcess
              {
              private void DoSomething()
              {
              NoddyProcess np = new NoddyProcess();
              np.GetValueFromString("foo");
              }
              }

              So putting all this together in the GetValueFromString method I need to access this.nc and using the passed string retrieve the value of this.nc.foo and return it to the caller. I am assuming that this can be done with reflection, however I seem to have hit a wall on this and could do with a prod in the right direction. P.S. I realise that in the examples given above none of this is actually necessary, however these are extemely simplfied versions of a much more complex framework.

              K Offline
              K Offline
              Kasdoffe
              wrote on last edited by
              #6

              This appeared to work for me, and I think it's what you want, using reflection. Note the Main method and GetValueFromString method. (Sorry for the formatting) using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace ConsoleApplication1 { class Program { static void Main(string [] args) { NoddyProcess p = new NoddyProcess(); object o = p.GetValueFromString("foo"); Console.WriteLine(o.ToString()); o = p.GetValueFromString("bar"); Console.WriteLine(o.ToString()); Console.Read(); } } class NoddyClass { public string foo; public string bar; } class NoddyProcess { private NoddyClass nc; public NoddyProcess() { this.nc = new NoddyClass(); this.nc.foo = "thingys"; this.nc.bar = "doodars"; } public object GetValueFromString(string value) { FieldInfo info = nc.GetType().GetField(value,BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public ); return info.GetValue(nc); } } class AnotherNoddyProcess { private void DoSomething() { NoddyProcess np = new NoddyProcess(); np.GetValueFromString("foo"); } } }

              1 Reply Last reply
              0
              • M MrEyes

                Basically I have a library that has an encrypted XML file sat underneath it, when the library object is created it reads in, decrypts and deserialises the XML to an class level object. This object is then used within the library to drive various things. This library exposes a COM interface to allow none .NET applications to interact with it, and until today these external applications did not require the ability to directly extract data from the XML file. Today however, this functionality is now a requirement. The XML itself while structurally simple, contains alot of elements. In fact it looks something like this:

                <Data>
                <Element1></Element1>
                <Element2></Element2>
                ....
                ....
                <Element1000></Element1000>
                </Data>

                Due to the volume of elements it isnt really feasible to create an externally accessible property for every single one, i.e:

                public string GetElement1Value
                {
                return this.myXmlObject.Element1
                }

                There was also the option of not using the current XML object in memory, re-reading, re-decrypting it, and then using XmlDocument and Xpath to get the value, however I belive the overhead here would be greater than using reflection. So this is where the idea of using reflection comes in. In fact since posting I have found a solution, so this is what I am currently trying out:

                public string GetConfigurationValue(string key)
                {
                Type itemType = typeof(MyXmlObject);

                PropertyInfo property = itemType.GetProperty(key);
                
                if (property == null)
                {
                    throw new ArgumentException("Invalid XML element key", key);
                }
                
                return property.GetValue(this.myXmlObject, null).ToString();
                

                }

                Which as you can see is alot shorter than using 1000+ property accessor/methods. Maybe I am barking up the wrong tree here, so feel free to point out something that I have considered as I have to admit using reflection doesnt sit very well with me.

                P Offline
                P Offline
                Patrick Etc
                wrote on last edited by
                #7

                Ack.. you may want to reconsider this approach. Did you know that you can use XPath queries in XML documents using the XmlDocument class in .NET? This might serve your purpose alot better than attempting to manually extract fields in this manner.


                The early bird who catches the worm works for someone who comes in late and owns the worm farm. -- Travis McGee

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups