Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the most specific method called based on type of parameter

Total OO noob question here. I have these two methods in a class

private void StoreSessionSpecific(LateSession dbSession, SessionViewModel session)
{
    session.LateSessionViewModel.Guidelines = dbSession.Guidelines.ToList();
}

private void StoreSessionSpecific(Session dbSession, SessionViewModel session )
{
        // nothing to do yet...
}

And when I call StoreSessionSpecific with dbSession being of type LateSession (LateSession inherits Session)

var dbSession = new LateSession();
StoreSessionSpecific(dbSession, session);

I expected the top one to be called. Since dbSession is of type LateSession.

@Paolo Tedesco This is how the classes are defined.

public class Session
{
    public int ID { get; set; }
    public int SessionTypeId { get; set; }
    public virtual SessionType SessionType { get; set; }
    [Required]
    public DateTime StartTime { get; set; }
    [Required]
    public DateTime EndTime { get; set; }
    // Session duration in minutes
    // public int SessionDuration { get; set; }
    public virtual ICollection<Attendee> Attendees { get; set; }

}

public class LateSession : Session
{


    public int MaxCriticalIncidentsPerUser { get; set; }
    public int MaxResultCriticalIncidents { get; set; }

    public virtual ICollection<Guideline> Guidelines { get; set; }


}
like image 764
Saab Avatar asked May 13 '11 13:05

Saab


1 Answers

Well, your assumption is plausible and there are languages where it had worked like you thought.

So does your code look like this:

Session s = new LateSession(); // the compiler only "knows" that s is of type Session
StoreSessionSpecific(s);

or does it look like this:

LateSession ls = new LateSession(); // the compiler knows that ls is in fact a LateSession
StoreSessionSpecific(ls);

In the first example the compiler prettends not to know what the actual type of "s" is and hard codes the invocation of the method with the Session argument. In the second example likewise the compiler generates a hard coded call to the other method.

In other languages the method call is "dynamic", that means during runtime the actuall types are considered. Methods that are polymorphic on their arguments are called "multimethods" (They are not only polymorphic on the class they are defined in but also on the arguments, hence "multi") (Edit: fixed typos)

like image 127
Angel O'Sphere Avatar answered May 31 '23 13:05

Angel O'Sphere