typeof question

  • Thread starter Thread starter MM
  • Start date Start date
M

MM

Very basic question:

string mystr

how do you test if it is a string?

Something like

if (mystr.GetType() == "System.String") <<< but this doesn't work.

Thanks for pointing me in the right direction.
 
Lookup the "AS" keyword. Example stright out of MSDN.

public static void Main()
{
object [] myObjects = new object[6];
myObjects[0] = new MyClass1();
myObjects[1] = new MyClass2();
myObjects[2] = "hello";
myObjects[3] = 123;
myObjects[4] = 123.4;
myObjects[5] = null;

for (int i = 0; i < myObjects.Length; ++i)
{
string s = myObjects as string;
Console.Write ("{0}:", i);
if (s != null)
Console.WriteLine ( "'" + s + "'" );
else
Console.WriteLine ( "not a string" );
}
}
}

Jason Newell, MCAD
Software Engineer
 
if(str.GetType().Equals(typeof(System.String)))
{
//true
}

HTH
Erick Sgarbi

-----Original Message-----
From: MM [mailto:[email protected]]
Posted At: Tuesday, 2 August 2005 8:23 AM
Posted To: microsoft.public.dotnet.languages.csharp
Conversation: typeof question
Subject: typeof question

Very basic question:

string mystr

how do you test if it is a string?

Something like

if (mystr.GetType() == "System.String") <<< but this doesn't work.

Thanks for pointing me in the right direction.
 
MM said:
Very basic question:

string mystr

how do you test if it is a string?

Something like

if (mystr.GetType() == "System.String") <<< but this doesn't work.

Thanks for pointing me in the right direction.

string s = "My String";
bool b = true;

if (s is string) <<< works for me, returns true.
if (b is string) <<< works for me, returns false.
if (b is bool) <<< works for me, returns true.

HTH,
Mythran
 
Erick Sgarbi said:
if(str.GetType().Equals(typeof(System.String)))
{
//true
}

Note that that will only work for "precise" matches. While it doesn't
matter for String (which is a sealed class anyway), that wouldn't help
if you wanted to know if a reference was a reference to an instance of
a Stream, and didn't care what kind of Stream it was. That's where
"is" (or "as") come in:

if (foo is Stream)
{
....
}
 
Jason Newell said:
Lookup the "AS" keyword. Example stright out of MSDN.

Using "as" just to check whether or not something is an instance of a
type isn't as straightforward as using "is". "as" is usually used when
you then want to use the cast version of the reference.
 
I concur.

Jason Newell

Using "as" just to check whether or not something is an instance of a
type isn't as straightforward as using "is". "as" is usually used when
you then want to use the cast version of the reference.
 
Back
Top