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. Dynamically assign values to instance

Dynamically assign values to instance

Scheduled Pinned Locked Moved C#
csharplinqperformancetutorialquestion
20 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.
  • S Stevo Z

    Hi Guys, I'd like to dynamically assign values to a known class instance based on the Property name. An example describes perfectly what I want to do: There is a class

    public class AClass
    {
    public string _aValue;

        public string AValue
        {
            get { return \_aValue; }
            set { \_aValue = value; }
        }
    }
    

    and I want to assing value to AClass.AValue without actually explicitly writing:

    AClass aInstance = new AClass();
    aInstance.AValue = "value";

    and now comes the best part. I'd like to avoid reflection as much as possible, because performance matters. I could go and look for a property named "AValue" and do

    typeof(AClass).GetProperty("AValue").SetValue(aInstance, "value", null);

    however that's veery slow. It's got to be possible to do that some other way, Linq works like this and it's not slow. any ideas?

    zilo

    S Offline
    S Offline
    S Senthil Kumar
    wrote on last edited by
    #5

    Zilo(svk) wrote:

    and I want to assing value to AClass.AValue without actually explicitly writing

    It's difficult to answer without knowing why. Is it because you don't know the type at compile time?

    Regards Senthil [MVP - Visual C#] _____________________________ My Home Page |My Blog | My Articles | My Flickr | WinMacro

    S 1 Reply Last reply
    0
    • D DaveyM69

      If it's only the one property you could use an implicit operator overload.

      public class AClass
      {
      public AClass() : this(string.Empty) { }
      private AClass(string aValue)
      {
      AValue = aValue;
      }
      public static implicit operator AClass(string aValue)
      {
      return new AClass(aValue);
      }
      public string AValue
      {
      get;
      set;
      }
      }

      AClass aInstance = "Test String";
      Console.WriteLine(aInstance.AValue);

      Dave
      BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
      Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)

      S Offline
      S Offline
      Stevo Z
      wrote on last edited by
      #6

      Interesting idea, but... It's not only one, there will be many properties like this within AClass. And it needs to be done outside of constructor.

      zilo

      D 1 Reply Last reply
      0
      • S S Senthil Kumar

        Zilo(svk) wrote:

        and I want to assing value to AClass.AValue without actually explicitly writing

        It's difficult to answer without knowing why. Is it because you don't know the type at compile time?

        Regards Senthil [MVP - Visual C#] _____________________________ My Home Page |My Blog | My Articles | My Flickr | WinMacro

        S Offline
        S Offline
        Stevo Z
        wrote on last edited by
        #7

        Yes. I'm loading the class from dll as

        Assembly.LoadFile(string file);

        And I'd like to keep AClass as simple as possible, without any specific code to read or write values into it. It's just a data container.

        zilo

        S 1 Reply Last reply
        0
        • S Stevo Z

          Hi Guys, I'd like to dynamically assign values to a known class instance based on the Property name. An example describes perfectly what I want to do: There is a class

          public class AClass
          {
          public string _aValue;

              public string AValue
              {
                  get { return \_aValue; }
                  set { \_aValue = value; }
              }
          }
          

          and I want to assing value to AClass.AValue without actually explicitly writing:

          AClass aInstance = new AClass();
          aInstance.AValue = "value";

          and now comes the best part. I'd like to avoid reflection as much as possible, because performance matters. I could go and look for a property named "AValue" and do

          typeof(AClass).GetProperty("AValue").SetValue(aInstance, "value", null);

          however that's veery slow. It's got to be possible to do that some other way, Linq works like this and it's not slow. any ideas?

          zilo

          C Offline
          C Offline
          Calin Tatar
          wrote on last edited by
          #8

          Basically, you are searching for an alternative to Reflection, right? Calin

          S 1 Reply Last reply
          0
          • C Calin Tatar

            Basically, you are searching for an alternative to Reflection, right? Calin

            S Offline
            S Offline
            Stevo Z
            wrote on last edited by
            #9

            Kind of. Something that does the job but keeps the speed on same level as direct access.

            zilo

            C 2 Replies Last reply
            0
            • S Stevo Z

              Kind of. Something that does the job but keeps the speed on same level as direct access.

              zilo

              C Offline
              C Offline
              Calin Tatar
              wrote on last edited by
              #10

              I think you could try by using Dynamic Invocation. Calin

              S 1 Reply Last reply
              0
              • C Calin Tatar

                I think you could try by using Dynamic Invocation. Calin

                S Offline
                S Offline
                Stevo Z
                wrote on last edited by
                #11

                Do you suggest to create a method using reflection on the fly:

                void AssingAValue(AClass aInstance, object value)
                {
                aInstance.AValue = value;
                }

                and then just call this method?

                zilo

                C 1 Reply Last reply
                0
                • S Stevo Z

                  Do you suggest to create a method using reflection on the fly:

                  void AssingAValue(AClass aInstance, object value)
                  {
                  aInstance.AValue = value;
                  }

                  and then just call this method?

                  zilo

                  C Offline
                  C Offline
                  Calin Tatar
                  wrote on last edited by
                  #12

                  yes, so you can dynamically change the AValue property. Calin

                  1 Reply Last reply
                  0
                  • S Stevo Z

                    Yes. I'm loading the class from dll as

                    Assembly.LoadFile(string file);

                    And I'd like to keep AClass as simple as possible, without any specific code to read or write values into it. It's just a data container.

                    zilo

                    S Offline
                    S Offline
                    S Senthil Kumar
                    wrote on last edited by
                    #13

                    Well, LINQ knows the types of data objects at compile time, so there's no similarity there. Without reflection, I guess your best bet is emitting the IL directly[^].

                    Regards Senthil [MVP - Visual C#] _____________________________ My Home Page |My Blog | My Articles | My Flickr | WinMacro

                    S 1 Reply Last reply
                    0
                    • S Stevo Z

                      Interesting idea, but... It's not only one, there will be many properties like this within AClass. And it needs to be done outside of constructor.

                      zilo

                      D Offline
                      D Offline
                      DaveyM69
                      wrote on last edited by
                      #14

                      Maybe extension methods could work. Create an extension method ToAClass for each type, and also pass the AClass instance.

                      public static class ExtensionMethods
                      {
                      static public void SetAClass(this string value, AClass instance)
                      {
                      instance.AString = value;
                      }

                      static public void SetAClass(this int value, AClass instance)
                      {
                          instance.AInt = value;
                      }
                      

                      }
                      public class AClass
                      {
                      public string AString
                      {
                      get;
                      set;
                      }
                      public int AInt
                      {
                      get;
                      set;
                      }
                      }

                      AClass aInstance = new AClass();
                      "Test string".SetAClass(aInstance);
                      123.SetAClass(aInstance);

                      Dave
                      BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                      Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)

                      S 1 Reply Last reply
                      0
                      • D DaveyM69

                        Maybe extension methods could work. Create an extension method ToAClass for each type, and also pass the AClass instance.

                        public static class ExtensionMethods
                        {
                        static public void SetAClass(this string value, AClass instance)
                        {
                        instance.AString = value;
                        }

                        static public void SetAClass(this int value, AClass instance)
                        {
                            instance.AInt = value;
                        }
                        

                        }
                        public class AClass
                        {
                        public string AString
                        {
                        get;
                        set;
                        }
                        public int AInt
                        {
                        get;
                        set;
                        }
                        }

                        AClass aInstance = new AClass();
                        "Test string".SetAClass(aInstance);
                        123.SetAClass(aInstance);

                        Dave
                        BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                        Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)

                        S Offline
                        S Offline
                        Stevo Z
                        wrote on last edited by
                        #15

                        Anyhow, whether is it extension methods or not, I'll have to create them dynamically using reflection and then just call those methods. I think I have a better idea now, thanks

                        zilo

                        1 Reply Last reply
                        0
                        • S S Senthil Kumar

                          Well, LINQ knows the types of data objects at compile time, so there's no similarity there. Without reflection, I guess your best bet is emitting the IL directly[^].

                          Regards Senthil [MVP - Visual C#] _____________________________ My Home Page |My Blog | My Articles | My Flickr | WinMacro

                          S Offline
                          S Offline
                          Stevo Z
                          wrote on last edited by
                          #16

                          It doesn't have to, I'm using those classes to work with linq as well and it's working fine. Thanks for the suggestion, that looks to be the only way to go.

                          zilo

                          S 1 Reply Last reply
                          0
                          • S Stevo Z

                            It doesn't have to, I'm using those classes to work with linq as well and it's working fine. Thanks for the suggestion, that looks to be the only way to go.

                            zilo

                            S Offline
                            S Offline
                            S Senthil Kumar
                            wrote on last edited by
                            #17

                            Zilo(svk) wrote:

                            I'm using those classes to work with linq as well and it's working fine

                            Now I'm curious - can you paste a snippet of code that does that? I can't imagine LINQ working without you specifying the type somewhere (unless it's an anonymous type, of course).

                            Regards Senthil [MVP - Visual C#] _____________________________ My Home Page |My Blog | My Articles | My Flickr | WinMacro

                            S 1 Reply Last reply
                            0
                            • S S Senthil Kumar

                              Zilo(svk) wrote:

                              I'm using those classes to work with linq as well and it's working fine

                              Now I'm curious - can you paste a snippet of code that does that? I can't imagine LINQ working without you specifying the type somewhere (unless it's an anonymous type, of course).

                              Regards Senthil [MVP - Visual C#] _____________________________ My Home Page |My Blog | My Articles | My Flickr | WinMacro

                              S Offline
                              S Offline
                              Stevo Z
                              wrote on last edited by
                              #18

                              I ment the classes are not present withing the same solution or assembly when compiling the code. When working with linq, I'm using strong types. This is a sample of one of the classes:

                              [Table(Name = "Books")]
                              public partial class Book : IDALEntity
                              {
                              private int _BookId;
                              private string _Title;
                              private int _Price;
                              private int _PublisherID;

                                  public Book()
                                  {   }
                              
                                  \[Column(Storage = "\_BookId", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL", IsPrimaryKey = true)\]
                                  public int BookId
                                  {
                                      get
                                      {
                                          return this.\_BookId;
                                      }
                                      set
                                      {
                                         this.\_BookId = value;                 
                                      }
                                  }
                              

                              ...
                              }

                              zilo

                              S 1 Reply Last reply
                              0
                              • S Stevo Z

                                I ment the classes are not present withing the same solution or assembly when compiling the code. When working with linq, I'm using strong types. This is a sample of one of the classes:

                                [Table(Name = "Books")]
                                public partial class Book : IDALEntity
                                {
                                private int _BookId;
                                private string _Title;
                                private int _Price;
                                private int _PublisherID;

                                    public Book()
                                    {   }
                                
                                    \[Column(Storage = "\_BookId", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL", IsPrimaryKey = true)\]
                                    public int BookId
                                    {
                                        get
                                        {
                                            return this.\_BookId;
                                        }
                                        set
                                        {
                                           this.\_BookId = value;                 
                                        }
                                    }
                                

                                ...
                                }

                                zilo

                                S Offline
                                S Offline
                                S Senthil Kumar
                                wrote on last edited by
                                #19

                                Well, LINQ uses reflection to read the custom attributes you provide for each property, so that it can map them to database columns. I guess they do it just once and then generate dynamic code to do the actual translation from SQL results to object property assignments.

                                Regards Senthil [MVP - Visual C#] _____________________________ My Home Page |My Blog | My Articles | My Flickr | WinMacro

                                1 Reply Last reply
                                0
                                • S Stevo Z

                                  Kind of. Something that does the job but keeps the speed on same level as direct access.

                                  zilo

                                  C Offline
                                  C Offline
                                  Calin Tatar
                                  wrote on last edited by
                                  #20

                                  Also, you can use TypeDescriptor, and PropertyDescriptor. Calin

                                  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