IS & AS IN c#

WHAT IS THE USE OF "IS" & "AS" WORDS IN C#?

Page 1 of 1

2 Replies - 611 Views - Last Post: 03 December 2009 - 05:24 PM Rate Topic: -----

#1 Handsomeboy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 02-December 09

IS & AS IN c#

Posted 02 December 2009 - 02:57 AM

I have a problem and i dont know what is the real use of these words i know that they are used to show that an instance of
a class is from a special type but i wonder why should it be defined ?
Is This A Good Question/Topic? 0
  • +

#3 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1526
  • View blog
  • Posts: 5,961
  • Joined: 21-March 08

Re: IS & AS IN c#

Posted 02 December 2009 - 05:46 AM

some sample code...

// looping through all controls on a form
foreach (Control c in this.Controls)
{
     if (c is Button)
     {
          // I only want to deal with buttons
          Button btn = c as Button;
     }
}



this same code could be written like this without using AS and IS...

foreach (Control c in this.Controls)
{
     if (c.GetType() == typeof(Button))
     {
          // I only want to deal with buttons
          Button btn = (Button)c;
     }
}



It basically makes it more readable.
Was This Post Helpful? 1

#4 FlashM  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 382
  • View blog
  • Posts: 1,195
  • Joined: 03-December 09

Re: IS & AS IN c#

Posted 03 December 2009 - 05:24 PM

There is one more difference between IS and AS.

1. If you compare two objects using IS keyword, your return value if TRUE/FALSE
2. If you convert some object to other object using AS keyword, your return value is NULL if converting is not successful.

Example:
Button btn = btnConvert;
foreach (Control c in this.Controls)
{
	if ((btn = c as Button) != null)
	{
		btn.Text = "updated";
	}
}


This post has been edited by FlashM: 03 December 2009 - 05:25 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1