Advertisement
d0ntth1nc

Untitled

Jan 19th, 2015
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.71 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Test
  4. {
  5.     class Person { }
  6.  
  7.     class Student : Person { }
  8.  
  9.     class MainClass
  10.     {
  11.         public static void Main(string[] args)
  12.         {
  13.             Student student = new Student();
  14.             Person studentAsPerson = student;
  15.             Person justPerson = new Person();
  16.  
  17.             if (student is Student)
  18.             {
  19.                 Console.WriteLine("This instance is subclass/class of Student");
  20.             }
  21.  
  22.             if (studentAsPerson is Student)
  23.             {
  24.                 // This will set 's' to null if studentAsPerson is not subclass/class of Student!
  25.                 var s = studentAsPerson as Student;
  26.  
  27.                 // This will throw error if studentAsPerson is not subclass/class of Student!
  28.                 var st = (Student)studentAsPerson;
  29.                 Console.WriteLine("This instance is subclass/class Student");
  30.             }
  31.  
  32.             if (student is Person)
  33.             {
  34.                 Console.WriteLine("This instance is subckass/class of Person");
  35.             }
  36.  
  37.             if (studentAsPerson is Person)
  38.             {
  39.                 Console.WriteLine("This instance is subclass/class of Person");
  40.             }
  41.  
  42.             if (studentAsPerson.GetType() == typeof(Student))
  43.             {
  44.                 Console.WriteLine("This object is instance of class Student!");
  45.             }
  46.  
  47.             if (justPerson is Student) //false
  48.             {
  49.                 Console.WriteLine("Hell no!");
  50.             }
  51.  
  52.             if ((justPerson as Student) == null) // person is not subclass of student!
  53.             {
  54.                 Console.WriteLine("Cannot convert person to student!");
  55.             }
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement