Results 1 to 15 of 15

Thread: How to get instance of extended object at runtime

Threaded View

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Aug 2000
    Posts
    1,091

    How to get instance of extended object at runtime

    I'm not even sure the title correctly explains the situation that I'm running into, but I'll try my best to describe it.

    I've got the following classes defined:

    public class AccountBase
    public class ExtendedAccount1 : AccountBase
    public class ExtendedAccount2 : AccountBase

    I have a method such as:

    Code:
    public void AddAccount(AccountBase account)
    {
         var o = <convert account into actual extended account type>  <-- how to do this?
         thirdPartyLibrary.DoSomething(o);
    }
    Somehow in AddAccount, I need to be able to create an instance of the 'account' object as the extended type that was passed in, without having to resort to an if or switch statement to determine what type 'account' actually is.

    The reason I need to do this is because third party library that I'm using is only "seeing" AccountBase when I pass in ExtendedAccount1 or ExtendedAccount2. I need it to actually "see" the full extended class.

    DoSomething is defined as:

    public T DoSomething<T>(
    T value
    )

    I know I can do something like:
    Code:
    public void AddAccount(AccountBase account)
    {
         if(account Is ExtendedAccount1)
         {
               thirdPartyLibrary.DoSomething((ExtendedAccount1)account);
         } else if(account Is ExtendedAccount2)
         {
               thirdPartyLibrary.DoSomething((ExtendedAccount2)account);
         }
    }
    But I REALLY don't want to do this because then I would have to maintain this block of code every time I added a new extended account type. I'm really hoping to make this as generic as possible.

    Is this possible? Example code would be greatly appreciated.
    Last edited by softwareguy74; Feb 19th, 2014 at 09:58 PM.

    Visual Studio 2010

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width