For Programmers: Free Programming Magazines  


Home > Archive > C# > June 2006 > [C#] Casting from derived class to base class









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author [C#] Casting from derived class to base class
Melon00

2006-06-06, 10:53 am

I have a class I am calling SimTreeNode which is a System.Windows.Forms.TreeNode type. I am planning on using this class within my TreeView class.

Class Definition:

code:
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace SimTree { public class SimTreeNode : System.Windows.Forms.TreeNode { //public static explicit operator SimTreeNode(TreeNode tn) //{ //} } }


As you can see, I don't do anything more or less than the TreeNode class.

The problem is, when I try to use my SimTreeNode in place of any TreeNode in my TreeView class, it throws runtime errors.

Here is the snippet of code I am doing the conversion.
code:
using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.Xml; using System.Xml.Serialization; using SimTree.Properties; using System.Runtime.InteropServices; namespace SimTree { public partial class SimTree : System.Windows.Forms.TreeView { private void SimTree_ItemDrag(object sender, ItemDragEventArgs e) { // Do not allow anything other than devices to be dragged Point pt = this.PointToClient(Control.MousePosition); SimTreeNode tn = (SimTreeNode)this.GetNodeAt(pt); // <--- Runtime error here ... } } }


Runtime Error:

code:
Unable to cast object of type 'System.Windows.Forms.TreeNode' to type 'SimTree.SimTreeNode'.


I would like to know why I cant caste my derived type to my base type.

According to a million online forums, I don't need to make an explicit operator to caste to/from base types. I actually tried to make an explicit caste operator if you look at my comments in the SimTree.SimTreeNode class, but gave me a compiler error:

code:
Error 1 'SimTree.SimTreeNode.explicit operator SimTree.SimTreeNode(System.Windows.Forms.TreeNode)': user-defined conversion to/from base class C:\...\SimTree\SimTreeNode.cs 10 23 SimTree


This really doesn't make any sense to me as the compiler SHOULDN'T have anyway of telling how to convert a base type to a derived type without me telling it explicitly.

I am hitting brick walls left and right with this simple thing I want to do.
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com