Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there pointer in C# like C++? Is it safe?

I'm writing an application that work with a tree data structure. I've written it with C++, now i want to write it by C#. I use pointers for implementing the tree data structure. Is there a pointer in C# too? Is it safe to use it?

like image 453
masoud ramezani Avatar asked Feb 25 '10 11:02

masoud ramezani


People also ask

Why pointers are not used in C?

The reason is that pointers are used to bodge into C some vital features which are missing from the original language: arrays, strings, & writeable function parameters.

How many pointer does C have?

This is called levels of pointers. According to ANSI C, each compiler must have at least 12 levels of pointers. This means we can use 12 * symbols with a variable name.

Is pointer a keyword in C?

A pointer is NOT a keyword. [C]. A variable that stores address of other variable -> Correct. A pointer is a variable that stores the address of any other variable be it a value or another address.

What is pointer in C example?

A pointer is a variable that stores the address of another variable. Unlike other variables that hold values of a certain type, pointer holds the address of a variable. For example, an integer variable holds (or you can say stores) an integer value, however an integer pointer holds the address of a integer variable.


1 Answers

If you're implementing a tree structure in C# (or Java, or many other languages) you'd use references instead of pointers. NB. references in C++ are not the same as these references.

The usage is similar to pointers for the most part, but there are advantages like garbage collection.

class TreeNode {     private TreeNode parent, firstChild, nextSibling;      public InsertChild(TreeNode newChild)     {         newChild.parent = this;         newChild.nextSibling = firstChild;         firstChild = newChild;     } }  var root = new TreeNode(); var child1 = new TreeNode(); root.InsertChild(child1); 

Points of interest:

  • No need to modify the type with * when declaring the members
  • No need to set them to null in a constructor (they're already null)
  • No special -> operator for member access
  • No need to write a destructor (although look up IDisposable)
like image 115
Daniel Earwicker Avatar answered Sep 18 '22 15:09

Daniel Earwicker