© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
18 replies
steven preadly

Why does calling the PrintFullName() method require casting it as ((Employee)PTE).PrintFullName() ?

Hi, I have two classes where one inherits from the other. Here's the code. My question is: why do I need to cast the method PrintFullName() when calling it as ((Employee)PTE).PrintFullName()? Why can't it be cast directly like (Employee)PTE.PrintFullName()?
public class Employee 
{
    public string? firstName;
    public string? lastName;

    public virtual string PrintFullName()
    {
        //Console.WriteLine(firstName + " " + lastName);

        return firstName + " " + lastName;
    }
}

public class PartTimeEmployee: Employee 
{
    public new string PrintFullName() 
    {
        return firstName + " " + lastName + " "  + "contractor";
    }
}
public class Employee 
{
    public string? firstName;
    public string? lastName;

    public virtual string PrintFullName()
    {
        //Console.WriteLine(firstName + " " + lastName);

        return firstName + " " + lastName;
    }
}

public class PartTimeEmployee: Employee 
{
    public new string PrintFullName() 
    {
        return firstName + " " + lastName + " "  + "contractor";
    }
}

      PartTimeEmployee PTE = new PartTimeEmployee();
      PTE.firstName = "parttime";
      PTE.lastName = "Employee";
      ((Employee)PTE).PrintFullName();
      PartTimeEmployee PTE = new PartTimeEmployee();
      PTE.firstName = "parttime";
      PTE.lastName = "Employee";
      ((Employee)PTE).PrintFullName();
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Why is it not calling the OnCollisionEnter method?
C#CC# / help
3y ago
Why does this require a cast?
C#CC# / help
2y ago
✅ Method calling help
C#CC# / help
3y ago
❔ Calling async method
C#CC# / help
4y ago