Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between is and as keyword in c#

    • 0
    • 3
    • 3
    • 1
    • 0
    • 0
    • 0
    • 0
    • 274
    Comment on it

    The difference between is and as operator is that:

    An object can be cast to a certain type then is returns true otherwise false, but talking about as operator, it is used to cast an object to a specific type but if in any case it is unable to type cast that object, it returns Null.

    Ex.

        class Student
        {
            public int RollNumber { get; set; }
            public string Name { get; set; }
        }
    
        class RegularStudent : Student
        {
            public int MonthlyAttendance { get; set; }
        }
    
        class CorrespondenceStudent : Student
        {
            public int AnualAttendance { get; set; }
        }
    
    
    
        protected void checkIs()
        {
            Student student = new Student
            {
                RollNumber = 123,
                Name = "Gaurav"
            };
    
            // this will return true
            if (student is Student)
            {
                Response.Write(student.Name + " is a student");
            }
            else
            {
                Response.Write(student.Name + " is not a student");
            }
    
            //  this will return false
            if (student is RegularStudent)
            {
                Response.Write(student.Name + " is a regular student");
            }
            else
            {
                Response.Write(student.Name + " is not a regular student");
            }
        }
    
        protected void checkAs()
        {
            Student student = new Student
            {
                RollNumber = 123,
                Name = "Gaurav"
            };
    
            RegularStudent regularStudent = student as RegularStudent;
    
            // this will return true
            if (regularStudent == null)
            {
                Response.Write("Student is not a RegularStudent");
            }
            else
            {
                Response.Write("Student is a RegularStudent");
            }
    
        }
    

    Note : RegularStudent class is a derived type and the Base types to Derived type casting is not allowed but vise versa is possible.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: