Advertisement
Guest User

Polymorphism and List<T>

a guest
Mar 27th, 2025
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.07 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace Test.Program;
  5.  
  6. class BaseClass {
  7.     public virtual string TypeName => typeof(BaseClass).Name;
  8.    
  9.     public int BaseOnly => 1;
  10. }
  11.  
  12. class DerivedClass1 : BaseClass {
  13.     public override string TypeName => this.GetType().Name;
  14.    
  15.     public virtual string DerivedFrom => this.GetType()!.BaseType!.Name;
  16.    
  17.     public int Derived1Only => 2;
  18. }
  19.  
  20. class DerivedClass2 : DerivedClass1 {
  21.     public int Derived2Only => 3;
  22. }
  23.  
  24.  
  25. class Program
  26. {
  27.     static void Main() {
  28.         List<BaseClass> l = new();
  29.         l.Add(new BaseClass());
  30.         l.Add(new DerivedClass1());
  31.         l.Add(new DerivedClass2());
  32.        
  33.         l.ForEach(c => Console.WriteLine(c switch {
  34.             DerivedClass2 d2 => $"{d2.TypeName}:\tDerivedFrom = {d2.DerivedFrom}, Derived2Only = {d2.Derived2Only}",
  35.             DerivedClass1 d1 => $"{d1.TypeName}:\tDerivedFrom = {d1.DerivedFrom}, Derived1Only = {d1.Derived1Only}",
  36.             BaseClass     b  => $"{b.TypeName}:\t\tBaseOnly = {b.BaseOnly}"
  37.         }));
  38.     }
  39. }
Tags: polymorphism
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement