C
C#2y ago
max2451

pointers help

i want to make a function that swaps two ints using pointers but i get an error with the declaration of the function
14 Replies
max2451
max2451OP2y ago
this is mi code:
using System;

namespace Main {
class Program {
static void Main(string[] args) {
int a = 12;
int b = 21;

Console.WriteLine("a: {0} || b: {1}", a, b);

Console.WriteLine("a: {0} || b: {1}", a, b);
}

unsafe void Swap(int* a, int* b) {
int temp;
temp = *b;
*b = *a;
*a = *b;
}
}
}
using System;

namespace Main {
class Program {
static void Main(string[] args) {
int a = 12;
int b = 21;

Console.WriteLine("a: {0} || b: {1}", a, b);

Console.WriteLine("a: {0} || b: {1}", a, b);
}

unsafe void Swap(int* a, int* b) {
int temp;
temp = *b;
*b = *a;
*a = *b;
}
}
}
TheBoxyBear
TheBoxyBear2y ago
What is the error? Also for this purpose, I would recommend ref instead of pointers
max2451
max2451OP2y ago
it says Unsafe code may only appear if compiling with /unsafe what are refs?
TheBoxyBear
TheBoxyBear2y ago
You need to enable unsafe code in the project properties
Anton
Anton2y ago
set AllowUnsafeBlocks to true
Anton
Anton2y ago
or with tuples: (a, b) = (b, a)
max2451
max2451OP2y ago
how do i do that?
Anton
Anton2y ago
set that property to true in your csproj file
arion
arion2y ago
The tag will looks like this.
arion
arion2y ago
Though as Boxy said, the ref keyword doesn't require unsafe and does pretty much the same thing, its even marshalled into native code as a pointer i believe I believe the out keyword is also marshalled the same as a parameter return type
Connor
Connor2y ago
This is really unnecessary for what it’s trying to accomplish
FusedQyou
FusedQyou2y ago
I wonder what the point of this is anyway. I feel like an explanation why you need this in general is needed It's very rare you actually need pointers
Want results from more Discord servers?
Add your server