check for type=string

  • Thread starter Thread starter Anonymous
  • Start date Start date
A

Anonymous

Which is the recommended way in C# to test if an object is of type string?

In VB.NET I wrote "If TypeOf obj Is String Then".
That meets the requirements:
1. You don't have to instance an object.
2. Doesn't throw exception if obj is null.

I havn't found any solution to that in C#. Does it exist any simple syntax?
 
Anonymous said:
Which is the recommended way in C# to test if an object is of type string?

In VB.NET I wrote "If TypeOf obj Is String Then".
That meets the requirements:
1. You don't have to instance an object.
2. Doesn't throw exception if obj is null.

I havn't found any solution to that in C#. Does it exist any simple syntax?

Do you want it to return true if obj is a null reference? If so:

if (obj == null || obj is string)

Otherwise

if (obj is string)
 
Anonymous said:
Which is the recommended way in C# to test if an object is of type string?

In VB.NET I wrote "If TypeOf obj Is String Then".
That meets the requirements:
1. You don't have to instance an object.
2. Doesn't throw exception if obj is null.

I havn't found any solution to that in C#. Does it exist any simple syntax?

You can either use the is or as operator, depending on if you later have
use for a reference to the string:

if (obj is string) {
...
}

or

string s = obj as string;
if (s != null) {
...
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top