C#
C#

help

Root Question Message

Max2451
Max24511/9/2023
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
Max2451
Max24511/9/2023
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;
        }
    }
}
TheBoxyBear
TheBoxyBear1/9/2023
What is the error?
TheBoxyBear
TheBoxyBear1/9/2023
Also for this purpose, I would recommend ref instead of pointers
Max2451
Max24511/9/2023
it says Unsafe code may only appear if compiling with /unsafe
Max2451
Max24511/9/2023
what are refs?
TheBoxyBear
TheBoxyBear1/9/2023
You need to enable unsafe code in the project properties
AntonC
AntonC1/9/2023
set AllowUnsafeBlocks to true
AntonC
AntonC1/9/2023
or with tuples:
(a, b) = (b, a)
Max2451
Max24511/9/2023
how do i do that?
AntonC
AntonC1/10/2023
set that property to true in your csproj file
arion
arion1/10/2023
The tag will looks like this.
arion
arion1/10/2023
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
arion
arion1/10/2023
I believe the out keyword is also marshalled the same as a parameter return type
Playboi17
Playboi171/10/2023
This is really unnecessary for what it’s trying to accomplish
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy