PC Review


Reply
Thread Tools Rate Thread

check for type=string

 
 
Anonymous
Guest
Posts: n/a
 
      16th Jun 2008
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?
 
Reply With Quote
 
 
 
 
Jon Skeet [C# MVP]
Guest
Posts: n/a
 
      16th Jun 2008
Anonymous <(E-Mail Removed)> wrote:
> 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)

--
Jon Skeet - <(E-Mail Removed)>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
 
Reply With Quote
 
Göran Andersson
Guest
Posts: n/a
 
      16th Jun 2008
Anonymous wrote:
> 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) {
...
}

--
Göran Andersson
_____
http://www.guffa.com
 
Reply With Quote
 
 
 
Reply

Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Check, if string is convertable to another type Daniel Microsoft C# .NET 2 14th Jan 2004 01:53 PM
check, if string is convertable to another type Daniel Microsoft C# .NET 2 13th Jan 2004 12:51 PM
Cannot create an object of type 'System.String[]' from its string representation 'String[] Array' for the 'Options' property. Hessam Microsoft C# .NET 0 8th Aug 2003 09:45 AM
Cannot create an object of type 'System.String[]' from its representation 'String[] Array' Hessam Microsoft Dot NET 0 8th Aug 2003 09:36 AM
Cannot create an object of type 'System.String[]' from its representation 'String[] Array' Hessam Microsoft ASP .NET 0 8th Aug 2003 09:36 AM


Features
 

Advertising
 

Newsgroups
 


All times are GMT +1. The time now is 03:45 AM.