Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "->" in c#?

Tags:

syntax

c#

I have remembered that I have seen "->" used in C#. Apparently I cannot search it through Google (and I do not know what is the name). Therefore I would be very happy if you could explain it to me. Thanks.

like image 704
Petr Avatar asked Aug 08 '26 11:08

Petr


2 Answers

-> Accesses a member of a struct through a pointer.

See -> Operator

and

Pointer Types

using System;
struct Point
{
   public int x, y; 
}

class Test 
{
   public unsafe static void Main() 
   {
      Point pt = new Point();
      Point* pp = &pt;
      pp->x = 123;
      pp->y = 456;
      Console.WriteLine ( "{0} {1}", pt.x, pt.y );
   }
}

Outputs

123 456
like image 107
rahul Avatar answered Aug 11 '26 01:08

rahul


The -> operator is used for dereferencing pointers, and is used only in unsafe C# code.

Pointers are more or less like object references, except that they point to a memory address. It's a little closer to the internal workings of the system, but it puts garbage collection and type safety out of play. References are more abstract and more restrictive, but allow the runtime to guarantee type safety and do memory management.

See also this MSDN article about unsafe code: http://msdn.microsoft.com/en-us/library/t2yzs44b.aspx

like image 35
Thorarin Avatar answered Aug 11 '26 01:08

Thorarin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!