❔ Determine what variable is being referenced
I come from a primarily C++ background, and I take it C# is trying it's best to hold my hand and keep me from shooting myself in the foot, but I don't entirely understand local reference variables due to their limitations. In C++, I can determine whether a pointer is referencing something by comparing it's value against another address.
How would I accomplish the same thing with local reference variables in C#?
9 Replies
that doesnt sound very c#-ish
whats the use case here?
I've got a function that finds the nth space in a string and the space after that so I can underline a word in a console output. When it finds the nth space, it stores the index in one variable and switches to the second variable
Something to this effect
I know there are other ways to go about it but trying to implement it this way just begged the question
that sounds a lot like u want to use but u can also simply compare that was wrong
tbh u dont understand why u need refs at all there, just indices should be enough?
Span<T>
and especially its slice method (https://learn.microsoft.com/en-us/dotnet/api/system.span-1.slice?view=net-7.0)
ref
s:
(will print False True)It saves a few branches
to me that seems to be 2
IndexOfAny
calls (https://learn.microsoft.com/en-us/dotnet/api/system.string.indexofany?view=net-7.0) to geth the indices (or even just IndexOf
because u seem to care only about the space), no need to reinvent the wheelThat'd definitely be better than the looping approach
I was moreso curious if there was a way to overcome that limitation of C# references, but if it really is as simple as "there isn't one" then ah well I can always import some dll function if I need to
You would have to use
Unsafe.AreSame<int>(ref someRef, ref someVar)
(https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.unsafe.aresame?view=net-7.0#system-runtime-compilerservices-unsafe-aresame-1(-0@-0@)) to compare the references in this case. You don't want to use ReferenceEquals(someRef, someVar)
due to boxing for value types.Unsafe.AreSame(T, T) Method (System.Runtime.CompilerServices)
Determines whether the specified managed pointers point to the same location.
Oh sick
That works I'll bear that in mind if this comes up again
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.