Using is operator to check object type - CSharp Custom Type

CSharp examples for Custom Type:is

Description

Using is operator to check object type

Demo Code

using System;/*from  www.j a va 2s.c o  m*/
using System.Collections.Generic;
using System.Text;
public class Person
{
   private string _firstName;
   public string FirstName
   {
      get
      {
         return _firstName;
      }
   }
   private string _lastName;
   public string LastName
   {
      get
      {
         return _lastName;
      }
   }
   public int Age { get; set; }
   public Person(string firstName , string lastName, int age)
   {
      _firstName = firstName;
      _lastName = lastName;
      Age = age;
   }
}
public class Student : Person
{
   public string University { get; set; }
   public double Grade { get; set; }
   public Student(string firstName, string lastName, int age, string university, double grade) : base(firstName, lastName, age)
   {
      University = university;
      Grade = grade;
   }
}
class Program
{
   static void Main(string[] args)
   {
      Person p = new Person("A", "B", 32);
      if(p is Person)
      {
         Console.WriteLine("p is a Person");
      }
      else
      {
         Console.WriteLine("p is not a Person");
      }
      Student s = new Student("Ann", "Smith", 21, "MIT", 9);
      if(s is Student)
      {
         Console.WriteLine("s is a Student");
      }
      else
      {
         Console.WriteLine("s is not a Student");
      }
      if(s is Person)
      {
         Console.WriteLine("s is a Person");
      }
      else
      {
         Console.WriteLine("s is not a Person");
      }
      if(p is Student)
      {
         Console.WriteLine("p is a Student");
      }
      else
      {
         Console.WriteLine("p is not a Student");
      }
   }
}

Result


Related Tutorials