tags:

views:

150

answers:

4

In Actionscript you can have a variable hold a reference to a class type and then compare an instance of a class to the variable with is. Example:

var a:Foo = new Foo();
var type:Class = Foo;

if(a is type){  //this is true
  //do something
}

Can you do something similar in C#? Or does the "is" keyword always have to be followed by a class?

+1  A: 

It could also be followed by an interface name.

CodeSavvyGeek
+10  A: 

see also the Type.IsInstanceOfType method in the .NET framework, if you want to test against a variable type

newacct
A: 

Data types are objects so both the following are valid in C#

if (value is String) ...

if (value is ExampleClass) ...
enbuyukfener
+1  A: 

.NET 2010 beta 2 : tested against FrameWork 4, 3.5 ("full" FrameWork versions, not "Client Profile" versions)

Given :

public class Foo
{
    public Foo() {}
}

And run-time execution of :

Foo myFoo = new Foo();

Console.WriteLine(myFoo is Foo);

Console.WriteLine(typeof(Foo).IsInstanceOfType(myFoo));

The Console.WriteLine statements both print "True" to the Console Window.

Why do you think this prints 'False to the Console Window :

Console.WriteLine(myFoo.GetType().IsInstanceOfType(typeof(Foo)));
BillW
Bill, I've seen your 'tested against framework 3.5' etc statement before. It personally distracts me from the actual answer, which is a shame, as the general quality of your answers is pretty high.
Jan Jongboom
@Jan I think it's useful information; many people still work with earlier FrameWork versions. I note when I use "Client" profiles : I've found cases in which that does make a difference. Since I'm using a beta VS 2010, I feel it's good to state that. This kind of information, I, personally, would appreciate seeing in any post. I frequently find answers on SO marked as correct, with multiple up-votes, with code that I can see "by eye" will not compile; I would like my public answers here always to be based on verification by coding ... until I become "Jon Skeet" :) Sorry if that disturbs you !
BillW