Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6674915
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T03:47:18+00:00 2026-05-26T03:47:18+00:00

me again. Sorry about this. Following on from my previous question (I think I

  • 0

me again. Sorry about this.

Following on from my previous question (I think I failed to adequately demonstrate the source of my confusion), here is the actual function I was writing:

/// <summary>
///     A b-tree node.
/// </summary>
public class BTreeNode
{
    /// <summary>
    ///     Create a new b-tree node.
    /// </summary>
    public BTreeNode()
    {

    }

    /// <summary>
    ///     The node name.
    /// </summary>
    public string Name
    {
        get;
        set;
    }

    /// <summary>
    ///     The left-hand child node.
    /// </summary>
    public BTreeNode Left
    {
        get;
        set;
    }

    /// <summary>
    ///     The right-hand child node.
    /// </summary>
    public BTreeNode Right
    {
        get;
        set;
    }
}

/// <summary>
///     Perform a breadth-first traversal of a b-tree.
/// </summary>
/// <param name="rootNode">
///     The b-tree's root node.
/// </param>
/// <param name="forEachNode">
///     An action delegate to be called once for each node as it is traversed.
///     Also includes the node depth (0-based).
/// </param>
public static void TraverseBreadthFirst<TNode>(this TNode rootNode, Action<TNode, int> forEachNode)
    where TNode : BTreeNode
{
    if (rootNode == null)
        throw new ArgumentNullException("rootNode");

    if (forEachNode == null)
        throw new ArgumentNullException("forEachNode");

    Queue<Tuple<TNode, int>> nodeQueue = new Queue<Tuple<TNode, int>>(3); // Pretty sure there are never more than 3 nodes in the queue.

    nodeQueue.Enqueue(new Tuple<TNode, int>(rootNode, 0));
    while (nodeQueue.Count > 0)
    {
        Tuple<TNode, int> parentNodeWithDepth = nodeQueue.Dequeue();
        TNode parentNode = parentNodeWithDepth.Item1;
        int nodeDepth = parentNodeWithDepth.Item2;

        forEachNode(parentNode, nodeDepth);
        nodeDepth++;

        if (parentNode.Left != null)
            nodeQueue.Enqueue(new Tuple<TNode, int>((TNode)parentNode.Left, nodeDepth));

        if (parentNode.Right != null)
            nodeQueue.Enqueue(new Tuple<TNode, int>((TNode)parentNode.Right, nodeDepth));
    }
}

I am not sure I see why the explicit cast to TNode is needed here:

nodeQueue.Enqueue(new Tuple<TNode, int>((TNode)parentNode.Left, nodeDepth));

Under what circumstances could parentNode.Left be something that is not assignable to TNode (given TNode is constrained to be of type BTreeNode or derived).

To put the question another way, under what circumstances could this function result in an InvalidCastException? If there isn’t one, then why does the compiler require an explicit cast?

Edit: I think I’m ok with changing the implementation to something like:

TNode leftNode = parentNode.Left as TNode;
Debug.Assert(leftNode != null || parentNode.Left == null, "Left child is more derived.");
if (leftNode != null)
    nodeQueue.Enqueue(new Tuple<TNode, int>(leftNode, nodeDepth));
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T03:47:19+00:00Added an answer on May 26, 2026 at 3:47 am

    parentNode.Left is only typed to be BTreeNode. There’s no guarantee that it’s the same as TNode. Imagine you had:

    class SpecialBTreeNode : BTreeNode
    class BoringBTreeNode : BTreeNode
    

    Now consider TraverseBreadthFirst<SpecialBTreeNode>(rootNode, ...). What’s to stop rootNode.Left from returning a BoringBTreeNode?

    // This is entirely valid...
    SpecialBTreeNode special = new SpecialBTreeNode();
    special.Left = new BoringBTreeNode();
    

    It sounds like you might want to make BTreeNode itself generic:

    public class BTreeNode<T> where T : BTreeNode<T>
    {
        public T Left { get; set; }
        public T Right { get; set; }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Sorry about my previous question. The question I have to answer is this: Body
Sorry to ask this question again but I tried several solutions on stackoverflow and
Sorry for asking it again, there are already some questions about this keyword. But
Sorry for opening this topic again, but thinking about this topic itself has started
I don't think this question has asked yet (most similar questions are about extracting
Sorry if it has been asked before, I can't find any question about this
i have a question about EF4 again :) sorry i can't find any thing
Sorry to bother again, but I really need help transforming this Python2 code into
Sorry for asking this again but ppl seem to connect csrf only with form
Sorry I missed and deleted earlier question on accident again. I have a situation,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.