Click here to Skip to main content
15,903,385 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Base Class:
C#
  public class BaseBooks     {

        [DataMember]
        public Guid BookID { get; set; }
        [DataMember]
        public string FourCorners { get; set; }
        //...many attributes
}


Child Class
C#
public class Books:BaseBooks
{
    public void Test()
    {
        List<BaseBooks> listBooks = new Entity.Books(_objUser).GetList();
        Books book;
        foreach (BaseBooks obj in listBooks )
        {
            book = new Books();
            book.BookID = obj.BookID ;
            book.FourCorners = obj.FourCorners ;
            //many many attributes.
            list.Add(book);
        }
    }
}


When BaseBook has many attributes, How to set attribute value to child class quickly in Test,Framework 4.0
Posted
Comments
ZurdoDev 1-Aug-14 8:25am    
What do you mean quickly? Each attribute has to be set.

Because it appears that you're using Entity Framework, you shouldn't need to initialize these variables and convert BaseBook to Book. I'm assuming that the "list" variable is of type List<books> in your code sample.

With that in mind, you just need to make use of the "as" instruction.

C#
public class Books:BaseBooks
{
    public void Test()
    {
        List<BaseBooks> listBooks = new Entity.Books(_objUser).GetList();
        foreach (BaseBooks obj in listBooks )
        {
            list.Add(obj as Books);
        }
    }
}


Or we can make this a bit more concise with LINQ:

C#
public void Test()
{
    List<BaseBooks> listBooks = new Entity.Books(_objUser).GetList();
    list.AddRange(listbooks.Select( x => x as Books).ToList());
}
 
Share this answer
 
You need to write a so-called copy constructor:

C#
public class Books:BaseBooks
{
  public Books(BaseBooks child)
  {
    BookID = child.BookID;
    // ... and so long 
  }
}
{


So you can later in your code instead of book = new Books(); just say:

C#
//book = new Books();
book = new Books(obj);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900