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;
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
:Then change
a
's type to be this class:This works because classes are reference types, and
a
holds a reference (similar to a pointer) to aIntWrapper
object.=
copies the reference totemp
, without creating a new object. Bothtemp
anda
refers to the same object.ref
localsThis is a simpler way, but it is only for local variables. You can't use this for a field for example.