Populate a Class using an almost identical class' data











up vote
3
down vote

favorite












I have two classes which should be exactly the same apart from 1 class needed another property.



Instead of re-writing all of the properties twice, I thought of inheriting all of the properties from BaseClass with just the one extra property in MyNewClass



 public class BaseClass
{
public int BaseProperty1 { get; set; }
public int BaseProperty2 { get; set; }
public int BaseProperty3 { get; set; }
}

public class MyNewClass: BaseClass
{
public int? ExtraProperty{ get; set; }
}


Since I already fill in all of the details for the original BaseClass in my function, It would be far easier to be able to use this instance of the class to fill in the details of the new instance of MyNewClass.



I hoped it would be as simple as the following, but unfortunately I get the error: System.InvalidCastException: 'Unable to cast object of type 'BaseClass' to type 'MyNewClass'.'



 MyNewClass myNewClass= new MyNewClass();
myNewClass = (MyNewClass)baseClass; //baseClass is alread populated at this point
myNewClass.ExtraProperty = 1;


Is there any way to quickly populate a class using another class which has one less property?



I could just set each property individually, but the class which I am using is quite large and it feels like bad practice.



Thanks in advance for any help.










share|improve this question






















  • Possible duplicate of Apply properties values from one object to another of the same type automatically?
    – eocron
    Nov 21 at 16:48










  • Hence the name, answers in linked question is type-independand, so you can copy baseClass to myNewClass regardless.
    – eocron
    Nov 21 at 16:49










  • PropertyCopy is a handy method, but in the above scenario, i would roll with the constructor solution. It might be more clear / better readable. Also if MyNewClass has only one constructor, a developer is forced to use it. ... out before 'opinion based' close votes ;D
    – nilsK
    Nov 21 at 16:54










  • See also stackoverflow.com/questions/9885644/…
    – Avner Shahar-Kashtan
    Nov 21 at 17:28















up vote
3
down vote

favorite












I have two classes which should be exactly the same apart from 1 class needed another property.



Instead of re-writing all of the properties twice, I thought of inheriting all of the properties from BaseClass with just the one extra property in MyNewClass



 public class BaseClass
{
public int BaseProperty1 { get; set; }
public int BaseProperty2 { get; set; }
public int BaseProperty3 { get; set; }
}

public class MyNewClass: BaseClass
{
public int? ExtraProperty{ get; set; }
}


Since I already fill in all of the details for the original BaseClass in my function, It would be far easier to be able to use this instance of the class to fill in the details of the new instance of MyNewClass.



I hoped it would be as simple as the following, but unfortunately I get the error: System.InvalidCastException: 'Unable to cast object of type 'BaseClass' to type 'MyNewClass'.'



 MyNewClass myNewClass= new MyNewClass();
myNewClass = (MyNewClass)baseClass; //baseClass is alread populated at this point
myNewClass.ExtraProperty = 1;


Is there any way to quickly populate a class using another class which has one less property?



I could just set each property individually, but the class which I am using is quite large and it feels like bad practice.



Thanks in advance for any help.










share|improve this question






















  • Possible duplicate of Apply properties values from one object to another of the same type automatically?
    – eocron
    Nov 21 at 16:48










  • Hence the name, answers in linked question is type-independand, so you can copy baseClass to myNewClass regardless.
    – eocron
    Nov 21 at 16:49










  • PropertyCopy is a handy method, but in the above scenario, i would roll with the constructor solution. It might be more clear / better readable. Also if MyNewClass has only one constructor, a developer is forced to use it. ... out before 'opinion based' close votes ;D
    – nilsK
    Nov 21 at 16:54










  • See also stackoverflow.com/questions/9885644/…
    – Avner Shahar-Kashtan
    Nov 21 at 17:28













up vote
3
down vote

favorite









up vote
3
down vote

favorite











I have two classes which should be exactly the same apart from 1 class needed another property.



Instead of re-writing all of the properties twice, I thought of inheriting all of the properties from BaseClass with just the one extra property in MyNewClass



 public class BaseClass
{
public int BaseProperty1 { get; set; }
public int BaseProperty2 { get; set; }
public int BaseProperty3 { get; set; }
}

public class MyNewClass: BaseClass
{
public int? ExtraProperty{ get; set; }
}


Since I already fill in all of the details for the original BaseClass in my function, It would be far easier to be able to use this instance of the class to fill in the details of the new instance of MyNewClass.



I hoped it would be as simple as the following, but unfortunately I get the error: System.InvalidCastException: 'Unable to cast object of type 'BaseClass' to type 'MyNewClass'.'



 MyNewClass myNewClass= new MyNewClass();
myNewClass = (MyNewClass)baseClass; //baseClass is alread populated at this point
myNewClass.ExtraProperty = 1;


Is there any way to quickly populate a class using another class which has one less property?



I could just set each property individually, but the class which I am using is quite large and it feels like bad practice.



Thanks in advance for any help.










share|improve this question













I have two classes which should be exactly the same apart from 1 class needed another property.



Instead of re-writing all of the properties twice, I thought of inheriting all of the properties from BaseClass with just the one extra property in MyNewClass



 public class BaseClass
{
public int BaseProperty1 { get; set; }
public int BaseProperty2 { get; set; }
public int BaseProperty3 { get; set; }
}

public class MyNewClass: BaseClass
{
public int? ExtraProperty{ get; set; }
}


Since I already fill in all of the details for the original BaseClass in my function, It would be far easier to be able to use this instance of the class to fill in the details of the new instance of MyNewClass.



I hoped it would be as simple as the following, but unfortunately I get the error: System.InvalidCastException: 'Unable to cast object of type 'BaseClass' to type 'MyNewClass'.'



 MyNewClass myNewClass= new MyNewClass();
myNewClass = (MyNewClass)baseClass; //baseClass is alread populated at this point
myNewClass.ExtraProperty = 1;


Is there any way to quickly populate a class using another class which has one less property?



I could just set each property individually, but the class which I am using is quite large and it feels like bad practice.



Thanks in advance for any help.







c# asp.net class






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 at 16:38









James Tordoff

3261219




3261219












  • Possible duplicate of Apply properties values from one object to another of the same type automatically?
    – eocron
    Nov 21 at 16:48










  • Hence the name, answers in linked question is type-independand, so you can copy baseClass to myNewClass regardless.
    – eocron
    Nov 21 at 16:49










  • PropertyCopy is a handy method, but in the above scenario, i would roll with the constructor solution. It might be more clear / better readable. Also if MyNewClass has only one constructor, a developer is forced to use it. ... out before 'opinion based' close votes ;D
    – nilsK
    Nov 21 at 16:54










  • See also stackoverflow.com/questions/9885644/…
    – Avner Shahar-Kashtan
    Nov 21 at 17:28


















  • Possible duplicate of Apply properties values from one object to another of the same type automatically?
    – eocron
    Nov 21 at 16:48










  • Hence the name, answers in linked question is type-independand, so you can copy baseClass to myNewClass regardless.
    – eocron
    Nov 21 at 16:49










  • PropertyCopy is a handy method, but in the above scenario, i would roll with the constructor solution. It might be more clear / better readable. Also if MyNewClass has only one constructor, a developer is forced to use it. ... out before 'opinion based' close votes ;D
    – nilsK
    Nov 21 at 16:54










  • See also stackoverflow.com/questions/9885644/…
    – Avner Shahar-Kashtan
    Nov 21 at 17:28
















Possible duplicate of Apply properties values from one object to another of the same type automatically?
– eocron
Nov 21 at 16:48




Possible duplicate of Apply properties values from one object to another of the same type automatically?
– eocron
Nov 21 at 16:48












Hence the name, answers in linked question is type-independand, so you can copy baseClass to myNewClass regardless.
– eocron
Nov 21 at 16:49




Hence the name, answers in linked question is type-independand, so you can copy baseClass to myNewClass regardless.
– eocron
Nov 21 at 16:49












PropertyCopy is a handy method, but in the above scenario, i would roll with the constructor solution. It might be more clear / better readable. Also if MyNewClass has only one constructor, a developer is forced to use it. ... out before 'opinion based' close votes ;D
– nilsK
Nov 21 at 16:54




PropertyCopy is a handy method, but in the above scenario, i would roll with the constructor solution. It might be more clear / better readable. Also if MyNewClass has only one constructor, a developer is forced to use it. ... out before 'opinion based' close votes ;D
– nilsK
Nov 21 at 16:54












See also stackoverflow.com/questions/9885644/…
– Avner Shahar-Kashtan
Nov 21 at 17:28




See also stackoverflow.com/questions/9885644/…
– Avner Shahar-Kashtan
Nov 21 at 17:28












3 Answers
3






active

oldest

votes

















up vote
4
down vote



accepted










Not every fruit is an apple, so from compiler perspective not every BaseClass is an instance of MyNewClass hence the cast fails.



There are couple of things you can do. For example use constructor to populate values:



public class MyNewClass : BaseClass
{
public int? ExtraProperty { get; set; }

public MyNewClass(BaseClass baseClass)
{
BaseProperty1 = baseClass.BaseProperty1;
BaseProperty2 = baseClass.BaseProperty2;
BaseProperty3 = baseClass.BaseProperty3;
}
}


Then you can do:



 var myNewClass = new MyNewClass(baseClass);
myNewClass.ExtraProperty = 1;





share|improve this answer



















  • 1




    I like this and I'm not the one that posted it.
    – Jabberwocky
    Nov 21 at 17:06


















up vote
0
down vote













If you have a lot of properties and don't want manually set every each of them then I suggest you iterate through them like this



public class MyNewClass : BaseClass
{
public MyNewClass(BaseClass seizeProperties)
{
PropertyInfo baseProperties = typeof(BaseClass).GetProperties();
foreach (PropertyInfo property in baseProperties)
{
property.SetValue(this, property.GetValue(seizeProperties));
}
}
public int? ExtraProperty { get; set; }
}





share|improve this answer




























    up vote
    0
    down vote













    "I already fill in all of the details for the original BaseClass in my function"

    So, if you have func like



    void your_func_fill(BaseClass _BaseClass)


    you can just call this func with child class object



    MyNewClass _MyNewClass;


    ...



    your_func_fill(_MyNewClass)


    Good luck!






    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53416724%2fpopulate-a-class-using-an-almost-identical-class-data%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      4
      down vote



      accepted










      Not every fruit is an apple, so from compiler perspective not every BaseClass is an instance of MyNewClass hence the cast fails.



      There are couple of things you can do. For example use constructor to populate values:



      public class MyNewClass : BaseClass
      {
      public int? ExtraProperty { get; set; }

      public MyNewClass(BaseClass baseClass)
      {
      BaseProperty1 = baseClass.BaseProperty1;
      BaseProperty2 = baseClass.BaseProperty2;
      BaseProperty3 = baseClass.BaseProperty3;
      }
      }


      Then you can do:



       var myNewClass = new MyNewClass(baseClass);
      myNewClass.ExtraProperty = 1;





      share|improve this answer



















      • 1




        I like this and I'm not the one that posted it.
        – Jabberwocky
        Nov 21 at 17:06















      up vote
      4
      down vote



      accepted










      Not every fruit is an apple, so from compiler perspective not every BaseClass is an instance of MyNewClass hence the cast fails.



      There are couple of things you can do. For example use constructor to populate values:



      public class MyNewClass : BaseClass
      {
      public int? ExtraProperty { get; set; }

      public MyNewClass(BaseClass baseClass)
      {
      BaseProperty1 = baseClass.BaseProperty1;
      BaseProperty2 = baseClass.BaseProperty2;
      BaseProperty3 = baseClass.BaseProperty3;
      }
      }


      Then you can do:



       var myNewClass = new MyNewClass(baseClass);
      myNewClass.ExtraProperty = 1;





      share|improve this answer



















      • 1




        I like this and I'm not the one that posted it.
        – Jabberwocky
        Nov 21 at 17:06













      up vote
      4
      down vote



      accepted







      up vote
      4
      down vote



      accepted






      Not every fruit is an apple, so from compiler perspective not every BaseClass is an instance of MyNewClass hence the cast fails.



      There are couple of things you can do. For example use constructor to populate values:



      public class MyNewClass : BaseClass
      {
      public int? ExtraProperty { get; set; }

      public MyNewClass(BaseClass baseClass)
      {
      BaseProperty1 = baseClass.BaseProperty1;
      BaseProperty2 = baseClass.BaseProperty2;
      BaseProperty3 = baseClass.BaseProperty3;
      }
      }


      Then you can do:



       var myNewClass = new MyNewClass(baseClass);
      myNewClass.ExtraProperty = 1;





      share|improve this answer














      Not every fruit is an apple, so from compiler perspective not every BaseClass is an instance of MyNewClass hence the cast fails.



      There are couple of things you can do. For example use constructor to populate values:



      public class MyNewClass : BaseClass
      {
      public int? ExtraProperty { get; set; }

      public MyNewClass(BaseClass baseClass)
      {
      BaseProperty1 = baseClass.BaseProperty1;
      BaseProperty2 = baseClass.BaseProperty2;
      BaseProperty3 = baseClass.BaseProperty3;
      }
      }


      Then you can do:



       var myNewClass = new MyNewClass(baseClass);
      myNewClass.ExtraProperty = 1;






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 22 at 18:18

























      answered Nov 21 at 16:43









      Fabjan

      9,37421439




      9,37421439








      • 1




        I like this and I'm not the one that posted it.
        – Jabberwocky
        Nov 21 at 17:06














      • 1




        I like this and I'm not the one that posted it.
        – Jabberwocky
        Nov 21 at 17:06








      1




      1




      I like this and I'm not the one that posted it.
      – Jabberwocky
      Nov 21 at 17:06




      I like this and I'm not the one that posted it.
      – Jabberwocky
      Nov 21 at 17:06












      up vote
      0
      down vote













      If you have a lot of properties and don't want manually set every each of them then I suggest you iterate through them like this



      public class MyNewClass : BaseClass
      {
      public MyNewClass(BaseClass seizeProperties)
      {
      PropertyInfo baseProperties = typeof(BaseClass).GetProperties();
      foreach (PropertyInfo property in baseProperties)
      {
      property.SetValue(this, property.GetValue(seizeProperties));
      }
      }
      public int? ExtraProperty { get; set; }
      }





      share|improve this answer

























        up vote
        0
        down vote













        If you have a lot of properties and don't want manually set every each of them then I suggest you iterate through them like this



        public class MyNewClass : BaseClass
        {
        public MyNewClass(BaseClass seizeProperties)
        {
        PropertyInfo baseProperties = typeof(BaseClass).GetProperties();
        foreach (PropertyInfo property in baseProperties)
        {
        property.SetValue(this, property.GetValue(seizeProperties));
        }
        }
        public int? ExtraProperty { get; set; }
        }





        share|improve this answer























          up vote
          0
          down vote










          up vote
          0
          down vote









          If you have a lot of properties and don't want manually set every each of them then I suggest you iterate through them like this



          public class MyNewClass : BaseClass
          {
          public MyNewClass(BaseClass seizeProperties)
          {
          PropertyInfo baseProperties = typeof(BaseClass).GetProperties();
          foreach (PropertyInfo property in baseProperties)
          {
          property.SetValue(this, property.GetValue(seizeProperties));
          }
          }
          public int? ExtraProperty { get; set; }
          }





          share|improve this answer












          If you have a lot of properties and don't want manually set every each of them then I suggest you iterate through them like this



          public class MyNewClass : BaseClass
          {
          public MyNewClass(BaseClass seizeProperties)
          {
          PropertyInfo baseProperties = typeof(BaseClass).GetProperties();
          foreach (PropertyInfo property in baseProperties)
          {
          property.SetValue(this, property.GetValue(seizeProperties));
          }
          }
          public int? ExtraProperty { get; set; }
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 at 17:06









          Max Jacobi

          183




          183






















              up vote
              0
              down vote













              "I already fill in all of the details for the original BaseClass in my function"

              So, if you have func like



              void your_func_fill(BaseClass _BaseClass)


              you can just call this func with child class object



              MyNewClass _MyNewClass;


              ...



              your_func_fill(_MyNewClass)


              Good luck!






              share|improve this answer

























                up vote
                0
                down vote













                "I already fill in all of the details for the original BaseClass in my function"

                So, if you have func like



                void your_func_fill(BaseClass _BaseClass)


                you can just call this func with child class object



                MyNewClass _MyNewClass;


                ...



                your_func_fill(_MyNewClass)


                Good luck!






                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  "I already fill in all of the details for the original BaseClass in my function"

                  So, if you have func like



                  void your_func_fill(BaseClass _BaseClass)


                  you can just call this func with child class object



                  MyNewClass _MyNewClass;


                  ...



                  your_func_fill(_MyNewClass)


                  Good luck!






                  share|improve this answer












                  "I already fill in all of the details for the original BaseClass in my function"

                  So, if you have func like



                  void your_func_fill(BaseClass _BaseClass)


                  you can just call this func with child class object



                  MyNewClass _MyNewClass;


                  ...



                  your_func_fill(_MyNewClass)


                  Good luck!







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 21 at 17:26









                  AndrewF

                  333




                  333






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53416724%2fpopulate-a-class-using-an-almost-identical-class-data%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Berounka

                      Sphinx de Gizeh

                      Different font size/position of beamer's navigation symbols template's content depending on regular/plain...