How to implement is functionality without using is keyword in C#
Last Updated :
01 May, 2019
Before implementing is operation without is keyword, let us have a brief outlook on how is keyword actually works.
is keyword
In C# is keyword is used to evaluate compatibility at runtime. It determines whether an object instance or the result of an expression can be converted to a specified type.
Syntax:
expr is type
Example: In the below code class Program class inherits a class c1 and in “if condition” the compatibility is checked using is operator which returns true.
using System;
namespace GeeksforGeeks {
class c1 {
}
class Program : c1
{
static void Main( string [] args)
{
Program pro1 = new Program();
if (pro1 is c1)
{
Console.WriteLine( "GeeksForGeeks" );
}
}
}
}
|
Is implementation without using is keyword
The similar functionality can be implemented using as keyword which returns
- null if the compatibility is not set
- and in case of compatible operands, it returns the LHS operand.
Example: In the below code, the object of c1 class is pro2 and thus cannot be assigned as an instance of Program class thus obj2 is set as null which later on is checked in if condition.
using System;
namespace GeeksforGeeks {
class c1 { }
class Program : c1
{
static void Main( string [] args)
{
Program pro1 = new Program();
c1 pro2 = new c1();
var obj1 = pro1 as c1;
var obj2 = pro2 as Program;
if (obj1 != null )
{
Console.WriteLine( "GeeksForGeeks" );
}
if (obj2 != null )
{
Console.WriteLine( "This Line will not be printed" );
}
}
}
}
|
Note: You can also find some significant differences between the is keyword and as keyword by going through the article Is vs As operator keyword in C#
Share your thoughts in the comments
Please Login to comment...