-2

I learn generics. Richter LinkedList. I have questions about class initialization. Added: There is 2 constructor. First with null. How we can do it with 1 one constructor?

internal sealed class Node<T> 
{
    public T m_data;
    public Node<T> m_next;

    public Node(T data) : this(data, null) 
    {
    }

    public Node(T data, Node<T> next) 
    {
        m_data = data; m_next = next;
    }

    public override String ToString() 
    {
        return m_data.ToString() + ((m_next != null) ? m_next.ToString() : String.Empty);
    }
}

What is?

public Node(T data) : this(data, null) 
{
}

especially (T data)

Why I can do?

 public Node(T data, Node<T> next)
        {
            m_data = data; m_next = null;
        }

But I can not do

 public Node(T data, Node<T> next)
        {
            m_data = null; m_next = next;
        }
streamc
  • 676
  • 3
  • 11
  • 27

2 Answers2

1

That's a example snipped from a LinkedList.

T is a placeholder for your type. So if you use Node<int> you set the type to be an integer - which is generic. data is the variable name within the constructor.

The usage of Node<int> foo = new Node<int>(1); is the same as List<int> foo = new List<int>(); which might be familiar to you

There is 2 constructor. First with null. How we can do it with 1 one constructor?

You can remove one if it isn't needet or set a default value like this to replace both:

public Node(T data, Node<T> next = null)
{
    m_data = data; m_next = next;
}
fubo
  • 44,811
  • 17
  • 103
  • 137
  • There is 2 constructor. First with null. How we can do it with 1 one constructor? – streamc Sep 29 '16 at 16:13
  • 1
    @ifooi updated my answer. If you're interested in LinkedList, i've implemented one recently http://codereview.stackexchange.com/questions/138142/linked-list-in-c – fubo Sep 30 '16 at 05:51
1

How we can do it with 1 one constructor?

You can use optional parameters in the constructor

internal sealed class Node<T> {
    public T m_data;
    public Node<T> m_next;

    public Node(T data, Node<T> next = null) {
        m_data = data;
        m_next = next;
    }

    public override String ToString() {
        return m_data.ToString() + ((m_next != null) ? m_next.ToString() : String.Empty);
    }
}

Which would allow for usage like

var node1 = new Node<string>("hello world"); //the same as (data, null)
var node2 = new Node<string>("how are you", node1);

What is public Node(T data) : this(data, null) ?

Its called constructor chaining/overloading.

Take a look at C# constructor chaining? (How to do it?)

Community
  • 1
  • 1
Nkosi
  • 235,767
  • 35
  • 427
  • 472