Cast From Abstract to decendant

T

tal_mcmahon

hi all,

if I have a class:


CODE

public abstract class Person
{
public string firstname;
public string lastname;

Person(string fname,string lname)
{
firstname=fname;
lastname=lname;
}
}


and I use it like this:


CODE

public class Employee : Person
{
public string ID;

public Employee(string fname,string lname,string
myid):base(fname,lname)
{
ID=myid;
}
}

Now I have a method that I pass the abstract class to


CODE
public void SendingMethod()
{
Employee emp = new Employee("biff","henderson","123");
mymethod(emp);
}


public void mymethod(Person p)
{
//code goes here
}

How do I access the ID on the employee?
I have tried:
p.ID,
(Employee)p.ID

when I watch the variable p i can see that it is of the type Employee
and that the ID is there.

I am sure it is a simple one but I havent used abstraction a lot and am
at a loss as to what to even search for.

Thanks in advance

Bassguy
 
N

Nicholas Paldino [.NET/C# MVP]

Bassguy,

Well, in essence, you don't, not with what you have now. The ID
property (which should be Id, not ID), is on the Employee class. The method
you pass the instance to takes a Person instance. If you need the Id
property, then you should move the definition of the Id to the abstract
class, so that all classes deriving from Person have it. Either that, or
have your method take an Employee instance, since it obviously expects that.

Hope this helps.
 
T

tal_mcmahon

maybe my model is the problem.

I am trying to implement a method that can accept a class derived from
my abstract class. and then I would sniff the class and operate on it
differently for each kind of derived class I use.

As I was trying to think of a response for your help (thanks for the
speed btw) It occurs to me that I should just overload the method and
pass in the derived classes. This would mean a new overload for each
drived class not an extension of a giant switch.

Here are my thoughts:


Old Idea:

class A{}

class B:A{}

class C:A{}

method(A a)
{

switch(a.GetType().Name)

case "B":
do B stuff
break;

case "C"
do C Stuff
break;
}
}

the new model would be

class A{}

class B:A{}

class C:A{}

method(B b)
{
do B stuff
}

method(C c)
{
do C stuff
}


any flaws with this??

Thx again
 
N

Nicholas Paldino [.NET/C# MVP]

Nope, that's exactly how I would do it. Much, MUCH cleaner, IMO.
 
T

tal_mcmahon

Tom,
Thanks I went with your method. works great!

Nicholas, your method only took the step away from the method I was
calling and placed the switch in the method that was doing the calling.
I am trying to always pass the abstract and then use the methods to
"sniff" what type the inherited item is to avoid recodes as new
decendants are created.

tal
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top