"Slicing" here refers to the C++ use of that term. For reference: What is object slicing?
I thought about this in the following context:
I have this Person:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name)
{
Name = name;
}
public override string ToString()
{
return Name;
}
public virtual void Greet()
{
Console.WriteLine("Hello!");
}
}
}
Teacher
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Teacher : Person
{
public Teacher() : base("empty")
{
}
public override void Greet()
{
base.Greet();
Console.WriteLine("I'm a teacher");
}
}
}
Student
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Student : Person
{
public Student() : base("empty")
{
}
public override void Greet()
{
base.Greet();
Console.WriteLine("I'm a student!");
}
}
}
and Main
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Student s = new Student();
Teacher t = new Teacher();
List<Person> persoane = new List<Person>();
persoane.Add(s);
persoane.Add(t);
foreach(Person person in persoane)
{
person.Greet();
}
}
}
}
I expected to see "Hello!" twice on the screen (because of this slicing concept) but I got Hello! I'm a student and Hello! I'm a teacher.
According to MS Docs, this is an implicit cast. But in C++, due to object slicing, I'm very much sure that I would've got "Hello!" twice.
So, my questions are: Does C# have slicing? Also, if I wanted to use Student and Teacher as a Person, how would I do that? (without changing the classes, only Main)
Thanks!