Search code examples
c#c++classpointerscall-by-value

anything like pointers in c#?


I'm new to c# (& coding in general) and i can't find anything pointer equivalent.
When i searched google i got something like safe/unsafe but that's not what i needed.

Like in c++ if you had a pointer and it pointed towards some value, the change in the pointer would cause change in the original variable. Is there anything of such in c#?
example-

static class universal
{
   public static int a = 10;
}

class class_a
{
   public void change1()
   {
      universal.a--;
   }
}

class class_b
{
   public void change2()
   {
      some_keyword temp = universal.a; //change in temp gives change in a
      temp-= 5; //the purpose of temp is to NOT have to write universal.a each time
   }
}

...

static void Main(string[] args)
{
   class_b B = new class_b();
   class_a A = new class_a();
   A.change1();
   Console.WriteLine(universal.a);//it will print 9

   B.change2();
   Console.WriteLine(universal.a);//it will print 4
   Console.ReadKey();
}

Edit- thank you @Sweeper i got the answer i had to use ref int temp = ref universal.a;


Solution

  • If you don't want unsafe code, I can think of two options.

    Wrapper object

    You can create a class like this, that wraps an int:

    public class IntWrapper {
        public int Value { get; set; }
    }
    

    Then change a's type to be this class:

    static class Universal
    {
       public static IntWrapper a = new IntWrapper { Value = 10 };
    }
    
    class class_a
    {
       public void change1()
       {
          universal.a.Value--;
       }
    }
    
    class class_b
    {
       public void change2()
       {
          Universal temp = universal.a; //change in temp gives change in a
          temp.Value -= 5;
       }
    }
    

    This works because classes are reference types, and a holds a reference (similar to a pointer) to a IntWrapper object. = copies the reference to temp, without creating a new object. Both temp and a refers to the same object.

    ref locals

    This is a simpler way, but it is only for local variables. You can't use this for a field for example.

    public void change2()
    {
        ref int temp = ref universal.a; //change in temp gives change in a
        temp -= 5;
    }