At the moment, I am trying to learn C#
through implementing various algorithms. I asked this question on how to represent a graph in C#
, and the user michaelb suggested to use classes. I tried to construct a graph with these classes in the following code.
I'm used to classes having a constructor, in which I can set the fields of the object I'm creating, but these classes only seem to have the default no-arguments constructors. I have three questions:
Are the "entities" in the classes even fields, e.g. does public Node From;
constitute a field in the Edge
class?
Isn't it weird that the classes Edge
and Node
refer to each other? It looks like a two-fold self-referential loop, in which they are defined in terms of each other.
When I try to run my code, I get the error at the step G.Nodes.Add(v1);
that says System.NullReferenceException
. What did I do wrong, and what would be the proper way of using these classes?
Thanks.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Graph G = new Graph();
Node v1 = new Node();
Node v2 = new Node();
Node v3 = new Node();
G.Nodes.Add(v1);
G.Nodes.Add(v2);
G.Nodes.Add(v3);
Edge e1 = new Edge();
Edge e2 = new Edge();
e1.From = v1;
e1.To = v2;
e2.From = v2;
e2.To = v3;
v1.EdgesOut.Add(e1);
v1.EdgesIn.Add(e1);
v2.EdgesOut.Add(e2);
v3.EdgesIn.Add(e2);
Console.WriteLine(G);
Console.ReadKey();
}
}
class Edge
{
public Node From;
public Node To;
}
class Node
{
public List<Edge> EdgesIn;
public List<Edge> EdgesOut;
}
class Graph
{
public List<Node> Nodes;
}