Advertisement
elena1234

How to convert one type object to another - change type ( class )

Apr 9th, 2021 (edited)
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.64 KB | None | 0 0
  1. using DefineAnInterfaceIPerson;
  2. using System;
  3.  
  4. namespace PersonInfo
  5. {
  6.    public class StartUp
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.             string name = Console.ReadLine();
  11.             int age = int.Parse(Console.ReadLine());
  12.  
  13.             IPerson person = new Citizen(name, age); // IPerson don't have method "SayHi()"
  14.             Console.WriteLine(person.Name);
  15.             Console.WriteLine(person.Age);
  16.  
  17.             Type type = person.GetType(); // how to change from one type to another
  18.             Citizen citizen = (Citizen)Convert.ChangeType(person, type);
  19.             citizen.SayHi();
  20.         }
  21.     }
  22. }
  23.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement