Solved

Invalid casting when going from Object to HyperLink

Posted on 2004-09-22
10
270 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
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
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
 
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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

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.
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

816 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

10 Experts available now in Live!

Get 1:1 Help Now