473,757 Members | 2,081 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Determine whether an object is derived from another object

Hi,

How can I determine whether an object is derived from another object?

My specific example is that I have a CustomError class with several specific
error types that derive from it (CustomBuinessE rror, CustomTechnical Error,
etc.). The CustomError base class has some extra fields that I want to log
or display when an error is handled.

I know I can check for exception types in Catch blocks. But what about in
the global.asax Application_Err or event? I retrieve the exception from the
Server object:

Exception exc = Server.GetLastE rror().GetBaseE xception();

1. How can I check for a specific exception type? ("is exc a
CustomTechnical Error?")

2. How can I check whether the exception derives from CustomError? In this
case I might want to print some fields from the CustomError (whether the
specific exception is CustomBuinessEr ror, CustomTechnical Error, or
whatever).

Thanks for any pointers,

Mark
Jun 15 '07 #1
9 3781
On Fri, 15 Jun 2007 12:43:27 -0700, Mark Berry <ma***@sorrynoe mail.com
wrote:
[...]
Exception exc = Server.GetLastE rror().GetBaseE xception();

1. How can I check for a specific exception type? ("is exc a
CustomTechnical Error?")

2. How can I check whether the exception derives from CustomError? In
this
case I might want to print some fields from the CustomError (whether the
specific exception is CustomBuinessEr ror, CustomTechnical Error, or
whatever).
It sounds like you want the "is" operator.

For example:

if (exc is CustomError)
{
CustomError ce = (CustomError)ex c;
// do some stuff with CustomError ce
}

Alternatively, the "as" operator:

CustomError ce = exc as CustomError;

if (ce != null)
{
// do some stuff with CustomError ce
}

Likewise the derived classes. Of course, all of the above assumes that
CustomError derives from Exception, which your post seems to imply it does.

Pete
Jun 15 '07 #2
"is" and "as", perhaps?
i.e.
if(error is CustomError) {...}
or
CustomError ce = error as CustomError;
if(ce!=null) {...}

(and ditto for CustomTechnical Error etc)

Personally I'd stick with the "Exception" suffix. In fact, I'd
probably stick to standard exceptions until I find an exceptional
exception; but there is a lot to be said for "ArgumentNullEx ception",
"ObjectDisposed Exception", etc.

Marc

Jun 15 '07 #3
Use the is or as keywords.

if (x is string) { string y = x as string; use y as a string... }

So:

catch (Exception e)
{
if (e is CustomTechnical Error)
{
CustomTechnical Error cte = e as CustomTechnical Error;
... use cte.
}
}

Difference between as keyword and casting (i.e. (CustomTechnica lError) e) is
that "as" will return null; casting will throw an exception if e is not the
correct type.

If you are in control of the derived exception classes then you could always
add an override for the ToString method and just use:

catch (CustomError ce)
{
Log (ce.ToString()) ;
}

As the ToString will call the respective virtual method on the class.

Each ToString override can build a string containing the information that
the specific instance provides which will i) make your code cleaner and ii)
provide easier extensibility should you add other exception classes.

HTH

- Andy

"Mark Berry" <ma***@sorrynoe mail.comwrote in message
news:u5******** ******@TK2MSFTN GP04.phx.gbl...
Hi,

How can I determine whether an object is derived from another object?

My specific example is that I have a CustomError class with several
specific error types that derive from it (CustomBuinessE rror,
CustomTechnical Error, etc.). The CustomError base class has some extra
fields that I want to log or display when an error is handled.

I know I can check for exception types in Catch blocks. But what about in
the global.asax Application_Err or event? I retrieve the exception from the
Server object:

Exception exc = Server.GetLastE rror().GetBaseE xception();

1. How can I check for a specific exception type? ("is exc a
CustomTechnical Error?")

2. How can I check whether the exception derives from CustomError? In this
case I might want to print some fields from the CustomError (whether the
specific exception is CustomBuinessEr ror, CustomTechnical Error, or
whatever).

Thanks for any pointers,

Mark

Jun 15 '07 #4
"Mark Berry" <ma***@sorrynoe mail.comwrote in message
news:u5******** ******@TK2MSFTN GP04.phx.gbl...
My specific example is that I have a CustomError class with several
specific error types that derive from it (CustomBuinessE rror,
CustomTechnical Error, etc.). The CustomError base class has some extra
fields that I want to log or display when an error is handled.
Don't use "is" or "as." Don't require the clients of an object to know which
specific class it belongs to.

Instead, use polymorphism. Create a virtual method that in the base class
which the derived classes override to do the "extra" stuff. In this case,
define one or more virtual methods like GetLogString() or
GetDisplayStrin g().

When your clients need to know what specific class they're working with, you
end up with maintenance problems when you add a new derived class. You have
to search your entire codebase for all the logic that's conditional upon the
results of "is" or "as." By using polymorphism, you keep all the differences
in one place - in the class that's defining the differences.

"is" and "as" should be avoided wherever possible in favor of polymorphism.
Sometimes they're necessary, but it doesn't seem like this is one of those
times.

///ark
Jun 15 '07 #5
If GetLastError() really has to return Exception, then you will have to
interrogate the object to see if it's a CustomError, via "is." But don't
make the clients go any farther down in the hierarchy, if at all possible.

///ark
Jun 15 '07 #6
On Fri, 15 Jun 2007 14:13:26 -0700, Mark Wilden <mw*****@commun itymtm.com>
wrote:
Don't use "is" or "as." Don't require the clients of an object to know
which
specific class it belongs to.

Instead, use polymorphism.
I do wholeheartedly agree with this advice. However, I'll point out that
it's not clear to me from the original post that this is practical in this
situation. I had the impression that he's receiving the exception in a
way that doesn't allow him to define the base type according to his own
type (that is, it always returns an Exception type object).

Sometimes you do need "is" or "as".

Pete
Jun 15 '07 #7
Thanks Marc. Actually I realized after typing the original post that I
should have been using the Exception suffix. Too lazy to retype ;).

I'm still new to .Net exception handling. I've been trying to follow and
extend Rob Bagby's webcast

http://blogs.msdn.com/bags/archive/2...e-and-ppt.aspx

I guess one argument for wrapping standard exceptions in custom exceptions
is that you can add contextual information e.g. current user name, etc. You
also get more granular control over how the Enterprise Library Application
Exception Block handles the exception, e.g ArgumentNullExc eption might be a
validation error on a user form, but a system error if an object is
unexpectedly null.

Mark

"Marc Gravell" <ma**********@g mail.comwrote in message
news:11******** **************@ a26g2000pre.goo glegroups.com.. .
"is" and "as", perhaps?
i.e.
if(error is CustomError) {...}
or
CustomError ce = error as CustomError;
if(ce!=null) {...}

(and ditto for CustomTechnical Error etc)

Personally I'd stick with the "Exception" suffix. In fact, I'd
probably stick to standard exceptions until I find an exceptional
exception; but there is a lot to be said for "ArgumentNullEx ception",
"ObjectDisposed Exception", etc.

Marc

Jun 15 '07 #8
Andy,

Thanks for the examples and especially for clarifying the use of "as" versus
a standard cast using parentheses.

Mark

"Andy Bates" <an**@ussdev.co mwrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
Use the is or as keywords.

if (x is string) { string y = x as string; use y as a string... }

So:

catch (Exception e)
{
if (e is CustomTechnical Error)
{
CustomTechnical Error cte = e as CustomTechnical Error;
... use cte.
}
}

Difference between as keyword and casting (i.e. (CustomTechnica lError) e)
is that "as" will return null; casting will throw an exception if e is not
the correct type.

If you are in control of the derived exception classes then you could
always add an override for the ToString method and just use:

catch (CustomError ce)
{
Log (ce.ToString()) ;
}

As the ToString will call the respective virtual method on the class.

Each ToString override can build a string containing the information that
the specific instance provides which will i) make your code cleaner and
ii) provide easier extensibility should you add other exception classes.

HTH

- Andy

"Mark Berry" <ma***@sorrynoe mail.comwrote in message
news:u5******** ******@TK2MSFTN GP04.phx.gbl...
>Hi,

How can I determine whether an object is derived from another object?

My specific example is that I have a CustomError class with several
specific error types that derive from it (CustomBuinessE rror,
CustomTechnica lError, etc.). The CustomError base class has some extra
fields that I want to log or display when an error is handled.

I know I can check for exception types in Catch blocks. But what about in
the global.asax Application_Err or event? I retrieve the exception from
the Server object:

Exception exc = Server.GetLastE rror().GetBaseE xception();

1. How can I check for a specific exception type? ("is exc a
CustomTechnica lError?")

2. How can I check whether the exception derives from CustomError? In
this case I might want to print some fields from the CustomError (whether
the specific exception is CustomBuinessEr ror, CustomTechnical Error, or
whatever).

Thanks for any pointers,

Mark


Jun 15 '07 #9
Wow guys thanks for all the answers and advice! I guess I found out where
all the smart people hang out ;).

I'm new to .Net exceptions and still trying to wrap my head around some
parts of it.

Yes, CustomException derives from Exception. I used the example of display
strings, but really I want to update an CustomException .ExceptionID property
that is defined as a GUID. I subsequently pass the exception to the
Enterprise Library (EL) Exception Handling Application Block, which logs the
exception including all its properties.

A little more background: this is a three-tier database application. I'm
trapping serious database exceptions in the Data Access Layer, wrapping them
in one of my CustomException s, logging them (via the EL), then re-throwing
them. (In the case of security exceptions, they are not re-thrown, but
rather a new dumbed-down exception is created and thrown.)

Eventually there will be various exception handlers in the business and
client tiers. However, for starters I am writing the "last chance" handler
in the global.asax Application_Err or block. Without this, the full exception
is displayed to the user in the browser.

In the Application_Err or block, I'll create a new CustomException and use
the EL to log it, then display a simplified message in the browser.

If the exception that I'm handling in the Application_Err or block is one of
my custom exceptions, I want to use the ExceptionID from that
CustomException in the new exception. That way, potentially multiple
exceptions in the event log(s) can be identified as having the same cause.

However, exceptions percolating up to the Application_Err or block are also
quite likely to be standard but unpredictable system exceptions (file locked
by another process, disk full, etc.). Those will also be wrapped and logged,
but they'll get a System.Guid.New Guid() in their
CustomException .ExceptionID.

So that's the long answer of why I need to know if the "exc" I get is a
CustomException or not. My understanding is that using "is" or "as" is
unavoidable in this case?

NOW, this brings up another question: what if I decide that I need to do
different things for different types of exceptions, whether they are system
exceptions or derived from CustomException ? For example, some exceptions may
not be fatal, so I can call Server.ClearErr or() and allow the user to
continue. However, others may mean I need to clean up and shut down. How
would I differentiate the different types of exceptions if not using "is" or
"as"? Or is it possible/advisable to use try - catch inside the
Application_Err or block?

Thanks again for the helpful discussion,

Mark

"Mark Wilden" <mw*****@commun itymtm.comwrote in message
news:%2******** ********@TK2MSF TNGP05.phx.gbl. ..
"Mark Berry" <ma***@sorrynoe mail.comwrote in message
news:u5******** ******@TK2MSFTN GP04.phx.gbl...
>My specific example is that I have a CustomError class with several
specific error types that derive from it (CustomBuinessE rror,
CustomTechnica lError, etc.). The CustomError base class has some extra
fields that I want to log or display when an error is handled.

Don't use "is" or "as." Don't require the clients of an object to know
which specific class it belongs to.

Instead, use polymorphism. Create a virtual method that in the base class
which the derived classes override to do the "extra" stuff. In this case,
define one or more virtual methods like GetLogString() or
GetDisplayStrin g().

When your clients need to know what specific class they're working with,
you end up with maintenance problems when you add a new derived class. You
have to search your entire codebase for all the logic that's conditional
upon the results of "is" or "as." By using polymorphism, you keep all the
differences in one place - in the class that's defining the differences.

"is" and "as" should be avoided wherever possible in favor of
polymorphism. Sometimes they're necessary, but it doesn't seem like this
is one of those times.

///ark

Jun 15 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
2888
by: Christopher W. Douglas | last post by:
I am writing a VB.NET application in Visual Studio 2003. I have written a method that handles several events, such as closing a form and changing the visible status of a form. I have some code that applies to all these events, but I need to have specific code execute when the form closes. The properties for this method are sender (the originator) and e (event arguments). I know how to get typeof (sender) to determine what form or...
5
2123
by: Jeff Greenberg | last post by:
Not an experienced c++ programmer here and I've gotten myself a bit stuck. I'm trying to implement a class lib and I've run into a sticky problem that I can't solve. I'd appreciate any help that I can get! Consider 3 classes in the following heirarchy: base / \ deriv1 deriv2 \
4
2963
by: John Baro | last post by:
I need to determine which fonts are human readable. Webdings, wingdings etc.. are not. Is there any easy way to accomplish this? Cheers JB
5
15237
by: Chris Capon | last post by:
Is there any way to cast a base class object to a derived class datatype when the derived class adds no new fields nor alters the object allocation in any way? The scenario would be where you want to extend a base class by adding only methods and properties, however, only base class objects are provided to you. Here is a sample: public class Base
11
2001
by: l.woods | last post by:
I want to set up my CATCH for a specific exception, but I really don't know which one of the multitude that it is. I am getting the exception now with Catch ex as Exception but I want to be more specific. I can't find any property of the exception object that tells me WHICH one it is. TIA,
11
2760
by: S. I. Becker | last post by:
Is it possible to determine if a function has been overridden by an object, when I have a pointer to that object as it's base class (which is abstract)? The reason I want to do this is that I want to call this function if it has been overridden, and not if it hasn't, e.g class CBase { public: virtual long mightBeOverridden(int i) { return 0; } // not a pure virtual function, since sub-classes should not have to define it
6
2844
by: noel.hunt | last post by:
I have a base class, PadRcv, with virtual functions. User code will derive from this class and possibly supply it's own functions to override the base class virtual functions. How can I test that a user-defined class has overriden the virtual function in the base class? I have code like this which compiles with gcc 2.95.4: Attrib Implicits(PadRcv *obj){ Attrib accum = 0;
6
5818
by: wink | last post by:
I'd like to determine if a method has been overridden as was asked here: http://www.velocityreviews.com/forums/t564224-determining-whether-a-derived-class-overrides-a-virtual-memberfunction.html The answer was can't do it, but I thought I'd ask here, my test code is: #include <iostream>
10
4112
by: blangela | last post by:
If I pass a base class object by reference (likely does not make a difference here that it is passed by reference) as a parameter to a derived class member function, the member function is not allowed to access the protected data members of the base object. This surprises me. Can someone explain why this is? I suspect there is a good reason and I am just having a slow day to not come up with it myself. Bob
0
9487
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9904
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9884
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8736
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7285
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5324
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3828
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3395
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2697
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.