Solved

Invalid casting when going from Object to HyperLink

Posted on 2004-09-22
10
268 Views
Last Modified: 2010-04-15
I'm trying to cast from an Object to a HyperLink but I get the invalid cast error message.  Here is my code:

Object newObject = new Object();                  
HyperLink Control1 = (HyperLink)newObject;

Why doesn't that work?  Shouldn't I be able to go from an Object to a Control?  This makes no sense.

0
Comment
Question by:joshkerr
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 15

Expert Comment

by:praneetha
ID: 12126551
Object newObject = new HyperLink()    
HyperLink Control1 = (HyperLink)newObject;

that will work
0
 

Author Comment

by:joshkerr
ID: 12126580
I'm asking a question about casting.  I am using the code above to try and demonstrate the problem in the simplest form.  I need to cast from an object to a hyperlink.
0
 
LVL 1

Accepted Solution

by:
blueforce earned 125 total points
ID: 12126711
Objects are the most generic types.

You can go from specific to generic but not necessarily the other way.

You must understand inheritance to see why.  Perhaps you've heard of the "Is A" relationships for Object Oriented Interitance?

A HyperLink IS A Object but an Object IS NOT A HyperLink.

Since a HyperLink class is created by inheriting from the Object class, you can not create a variable of type object and cast it to a hyperlink since Object is much more generic than a HyperLink.  In simple terms - how would the object know what to do as a hyperlink since it's just a generic object?

There is a big difference between the object's datatype and the instance of the object.  In praneetha's example, a variable is declared with type Object but an instance of the HyperLink class is created with it.  Since HyperLink IS AN Object, this will work and the instance "newObject" in the example will posess all of the characteristics of an object and a HyperLink.   Since Object is the base class for all classes in the .NET framework, you could declare any variable as type Object and create an instance of any other class with it.  That wouldn't be very smart though since it would defeat the purpose of early-binding and strongly typed variables.
0
 
LVL 15

Expert Comment

by:praneetha
ID: 12126742
i don't think you can do that...

it's liks saying object without hyperlink properties/methods cannot be cast back to hyperlink...

say object newobj="1"
Hyperlink control1=(hyperlink)newobj

since it does not know if newobj has any characteristics of hyperlink..




0
 

Author Comment

by:joshkerr
ID: 12126846
Okay, this is what I'm trying to do.  Maybe I should ask this as a separate question.  

When I initialize a control, I use the FindControl function to return a handle on the control.  If the control doesn't exist in the aspx page, then the FindControl returns null.  I want the FindControl function to return an empty control instead.  So I wrote a skinnedWebControl class and overrode the FindControl function to this:

public override Control FindControl(string id) {
           Control myControl = base.FindControl(id);
            if(myControl == null){
                Control newControl = new Control();
                return (Control)newControl;
            }
            else                  
                return myControl;
}

Unfortunately, this doesn't work because I get that casting error.   How else could I accomplish this?
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 15

Expert Comment

by:praneetha
ID: 12126872
which line do u get the error
0
 

Author Comment

by:joshkerr
ID: 12126917
// setup the objects
HyperLink hPMlink = (HyperLink)this.FindControl("PrivateMessagesLink");   ***Error
hPMlink.NavigateUrl = globals.messagePage;
hPMlink.Text = language.oRM.GetString("profile_privatemessages");
                  
0
 
LVL 15

Expert Comment

by:praneetha
ID: 12126943
   Control myControl = base.FindControl(id);
            if(myControl == null){
                Control newControl = new Control();
                return (Control)newControl;
            }
            else              
                return myControl;
instead of Control can u do HyperLink...and see what it yields
0
 
LVL 5

Expert Comment

by:tomasX2
ID: 12126946

This compiles... right?

You are getting a runtime exception.

This should work
            HyperLink h = HyperLink();
            object o = h;
            HyperLink h1 = (HyperLink)o;

This will not work because the object in question cannot be cast to a hyperlink...

Object newObject = new Object();              
HyperLink Control1 = (HyperLink)newObject;

To be able to cast between object they must have that kind of relationship...

Explicit Reference Conversions
The possible explicit reference conversions are

From object to any reference type.
From any class type B to any class type D, provided B is the base class of D
From any class type A to any interface type I, provided S is not sealed and do not implement I.
From any interface type I to any class type A, provided A is not sealed and implement I.
From any interface type I2 to any interface type I1, provided I2 is not derived from I1.
From System.Array to any array type.
From System.Delegate type to any delegate type.
From System.ICloneable to any array or delegate type.
Because of any reasons, if an explicit reference conversion fails, an InvalidCastException is thrown.



http://www.howtodothings.com/showarticle.asp?article=636

0
 
LVL 1

Expert Comment

by:blueforce
ID: 12126967
There's nothing wrong with this code:

public override Control FindControl(string id)
{
    Control myControl = base.FindControl(id);
    if(myControl == null)
    {
       Control newControl = new Control();
       return (Control)newControl;
     }
    else              
      return myControl;
}

I assume that you have the problem in the calling fn that expects a Control as a return value and then tries to cast that to  a HyperLink?

Without knowing what you're ultimately trying to accomplish, I can think of a couple of ways to handle this:

Ultimately, if you need a HyperLink, this:

       Control newControl = new Control();
       return (Control)newControl;

will never work.

If you're always looking for and always expecting a HyperLink, why not create a HyperLink to pass back in the FindControl method?  Otherwise, you could check the type of the control in the calling fn with myControl.GetType() to avoid casting from a Control to a HyperLink.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now