A Burch
A Burch

Reputation: 5

nested class used within base and derived classes

I'm getting a stack overflow exceptin in the setter of this code for Node from the nested data class

How should the nested data class Desc be handled in the base and derived classes, so that I can use this data in the new nodes created in the main window?

namespace Lib
{
    // Nested Data Class
    public class Desc
    {
        public Desc(string shape, Nullable<bool>[] inpins)
        {
            this.inpins = inpins;
        }
        string shape { get; set; }
        Nullable<bool>[] inpins { get; set; }
    }

    // Base class drived from ShapeNode class in vendor's framework
    public class Node : ShapeNode
    {
        public Node()
        {
        }

        // Make a copy of Node
        public Node(Node copy)
         : base(copy)
        {
          Text = copy.Text;
          NodeId = copy.NodeId;
        }

        public virtual Node Clone()
        {
           return new Node(this);
        }
       // Base Constructor
        public Node(string Text, Desc NodeId)
        {
           this.Text = Text;
           this.NodeId = NodeId;
        }
        new public string Text { get { return base.Text; } set { base.Text = value; } }
        public Desc NodeId { get { return NodeId; } set { NodeId = value; }
     }
}

   namespace Test
   {
   // Main Window code
public partial class MainWindow : Window
{
     public MainWindow()
     {
          InitializeComponent();
          nodes = new Node[]
          {   new A(
            "TESTA",
             new Desc(new Nullable<bool>[]{false, false})),
           new B(
             "TESTB",
              new Desc(new Nullable<bool>[] {false, false, false}))
          }
     }
 }

Upvotes: 0

Views: 183

Answers (2)

tukaef
tukaef

Reputation: 9214

Property getter (and setter) is just a method with special signature and name. So we can rewrite getter of NodeId as:

public Desc get_NodeId()
{   
    // recursive call
    return get_NodeId();
}

To solve this problem, just replace

public Desc NodeId { get { return NodeId; } set { NodeId = value; }}

by

public Desc NodeId { get; set; }

In this case we have (when this method isn't inlined):

public Desc get_NodeId()
{   
    // compiler-generated backing field
    return _nodeId; 
}

Upvotes: 2

paparazzo
paparazzo

Reputation: 45096

This is a loop and causes the a stack overflow exception

NodeId { get { return NodeId; } 

Use the answer from 2kay (+1) or use a private variable with another name

private Desc nodeID;

public Desc NodeId { get { return nodeID; } set { nodeID= value; }

Upvotes: 0

Related Questions