I have a class in C#, let's say:
public class COUNTRY
{
COUNTRY * neighbor;
string countryName;
}
C# is complaining that it can not point to itself (error code: CS0208)
This is allowed in C. For example:
typedef struct country
{
struct country *neighbor;
char[50] countryName;
} COUNTRY;
COUNTRY unitedNation[]
{
{COUNTRY a, "US"},
{COUNTRY b, "ABC"},
{COUNTRY c, "XYZ"},
{0,""}
}
COUNTRY a
{
{0, "Mexico"},
}
COUNTRY b
{
{0,"Findland"}
}
COUNTRY c
{
{0, "Australia"}
}
The structure defines a country with its neighbors.
unitedNation is a collection of many countries.
To simplify the issue, let's assume, a country can only have 1 or no neighbor. The variable of type COUNTRY could be easily initiated in C through declaration.
Does C# have similar ability?
CodePudding user response:
Classes are (usually) reference types. As such, you create instances with new
and when passed around in function calls, they are passed by "reference" (a fancy word for pointer). In contrast to reference types, there are also value types, which are passed by value, respectively.
So, what you try to do does not require special syntax.
using System;
namespace slist
{
class SList {
internal SList Next {get; set;}
internal SList() {
Next = null;
}
internal SList(SList head) {
this.Next = head;
}
internal int V {get; set;}
}
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("Hello World!");
SList head = new SList();
head.V = 1;
head = new SList(head);
head.V = 2;
head = new SList(head);
head.V = 3;
IterateSList(head);
}
static void IterateSList(SList head) {
SList current = head;
while (current != null) {
Console.WriteLine("{0:D}", current.V);
current = current.Next;
}
}
}
}
CodePudding user response:
First, define your class:
public class COUNTRY
{
public COUNTRY neighbor;
public string countryName;
}
Now, try this sample:
COUNTRY c1 = new COUNTRY();
c1.neighbor = c1;
c1.countryName = "Spain";
COUNTRY c2 = new COUNTRY();
c2.neighbor = c1;
c2.countryName = "France";
c1.neighbor = c2;
You can create c1
and set the neighbor reference to c1
itself. It's a non sense because Spain it's not a Spain neighbor but it's your "pointer", you can auto reference to this.
I create after a c2
, for France country, and set Spain as a neighbor.
Finally, I fix Spain neighbor, setting c2
(France).
I C#, when you use a class (not a struct), your variable is like a C pointer, it's a reference. In c1.neightbor = c1
you are setting the variable neightbor to the address of c1
. If you change c1.neightbor
, you really are changing c1
.