How to compare objects

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi guys!

I've a function that returns a System.Data.SqlClient.SqlException or
System.Int32 depending on the function's result. If occurs an error it
returns SQLException; if executes with no problem, it returns the @@IDENTITY
of the row which is an Int32 type.

Now I need to compare the type and give to the users the feedback. I ask
you: how can I compare objects. For example, if the function's result is a
SQLException or an Int32 type?

Is that technique right?

Thanks in advance
 
if (someobject.GetType()) == typeof(SqlException) ...

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Big things are made up of
lots of little things.
 
Andreiwid said:
I've a function that returns a System.Data.SqlClient.SqlException or
System.Int32 depending on the function's result. If occurs an error it
returns SQLException; if executes with no problem, it returns the @@IDENTITY
of the row which is an Int32 type.

Now I need to compare the type and give to the users the feedback. I ask
you: how can I compare objects. For example, if the function's result is a
SQLException or an Int32 type?

Is that technique right?

I wouldn't *return* the exception if an error occurs - I'd *throw* the
exception. You can then catch it in the error condition (preferrably
several stack frames up) or just look at the return value (as an int)
if there are no problems.
 
Kevin Spencer said:
if (someobject.GetType()) == typeof(SqlException) ...

Note that that would only return true if the object is *exactly* a
SqlException - not if it's *derived* from SqlException.

It's usually better to use:

if (someObject is SqlException)
....

or

SqlException e = someObject as SqlException
if (e != null)
....
 
Thanks a lot Kevin!

Adding information: VB.NET version

If TypeOf objSomeObject.GetType() Is System.Data.SqlClient.SqlException Then
...
ElseIf TypeOf...
...
Else ...
...
End If
 
Andreiwid said:
Thanks a lot Kevin!

Adding information: VB.NET version

If TypeOf objSomeObject.GetType() Is System.Data.SqlClient.SqlException Then
...
ElseIf TypeOf...
...
Else ...
...
End If

No, that will never work - because you're getting the type of the
return value of GetType(), which is always going to be System.Type,
never System.Data.SqlClient.SqlException

Just use

If TypeOf objSomeObject Is System.Data.SqlClient.SqlException

Or, as I said, just throw the exception.
 
True on all counts, Jon.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Big things are made up of
lots of little things.
 
Back
Top