Question

I found that in some places variable declarations like private int* myint ; I am not very sure what does * charactor in this syntax really do , Can someone please explain why this * charactor is used with data type in variable declarations ?

Was it helpful?

Solution

int* declares pointer to int type. C# supports pointer in unsafe context. We can use the unsafe keyword in two different ways. It can be used as a modifier to a method, property, and constructor etc. For example:

using System;
class MyClass
{
   public unsafe void Method()
   {
      int x = 10;
      int y = 20;
      int *ptr1 = &x;
      int *ptr2 = &y;
      Console.WriteLine((int)ptr1);
      Console.WriteLine((int)ptr2);
      Console.WriteLine(*ptr1);
      Console.WriteLine(*ptr2);
   }
}
class MyClient
{
   public static void Main()
   {
      MyClass mc = new MyClass();
      mc.Method();
   }
} 

The keyword unsafe can also be used to mark a group of statements as unsafe as shown below:

using System;
class MyClass
{
    public void Method()
    {
    unsafe
    {
        int x = 10;
        int y = 20;
        int *ptr1 = &x;
        int *ptr2 = &y;
        Console.WriteLine((int)ptr1);
        Console.WriteLine((int)ptr2);
        Console.WriteLine(*ptr1);
        Console.WriteLine(*ptr2);
    }
    }
}
class MyClient
{
    public static void Main()
    {
        MyClass mc = new MyClass();
        mc.Method();
    }
}

Reference: Pointers in C#

OTHER TIPS

It declares a pointer to an integer.

See for example: http://boredzo.org/pointers/ for a more in-depth explanation.

int is a value type. int* is a pointer type. Different concept altogether.

If you're not working with unsafe code, then you don't need to use pointer types.

It represents a pointer to a variable. Here is an example of getting and updating a variable via its pointer.

public class Program
{
    public static unsafe void Main(string[] args)
    {
        int foo = 10;
        int* fooPointer = &foo; //get the pointer to foo
        Console.WriteLine(foo); //here we can see foo is 10

        *fooPointer = 11; //update foo through the pointer
        Console.WriteLine(foo); //now foo is 11
    }
}

It creates a pointer variable. Meaning the variable points to the location in memory.

http://msdn.microsoft.com/en-us/library/y31yhkeb(v=vs.110).aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top