calling constructors

Hello again Experts,

is it possible to call different constructors based on the type of object passed into it?

for example:

public class A
{
     public A()
     {
          //default constructor
     }

     public A(ClassZ myObj)
     {
           //do something based on class ClassZ
     }

    public A(ClassY myObj)
    {
           //do something based on class ClassY
    }
}


client code:

   ClassZ objZ = new ClassZ();
   ClassY objY = new ClassY();

   A objA = new A(objZ);
           or
   A objA = new A(objY);

thanks




LVL 7
brdrokAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ryerrasCommented:
I think yeah. C# compiler would take care of it, as to which constructor to execute. This is nothing but method overloading
0
AaronReamsCommented:
Yes
0
tinchosCommented:
yes it is, and you can also call from one constructor to another one.

public class A
{
     public A()
     {
          //default initialization
     }

     public A(ClassZ myObj)
          : this()
     {
           //do something based on class ClassZ
     }

    public A(ClassY myObj)
          : this()
    {
           //do something based on class ClassY
    }
}

In that way if you call

new A( new ClassY() );

it would call the constructor that receives a ClassY object, then it would call the default constructor and then it would execute the rest of the constructor that receives a classYObject

Hope this helps

Tincho
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
brdrokAuthor Commented:
thanks...
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.