Object passed by reference unexpectedly
Why is the context of
a
modified when context
is modified?
21 Replies
Presumably,
TokenContext
is a class
, yes?yes
Well, that's how classes work
Classes are also known as reference types
Do you know C?
yes, I'm used to c++
Ok, so
TokenContext context
is actually TokenContext* context
In C#, that's the difference between a struct
and a class
A class
is a reference type, and always allocated on the heap
A variable referring to one is actually a pointer to heap dataright, so I should almost never use classes then I suppose
No, that is exactly the wrong approach
C# is a GC language. Automatic memory management is the whole point
so then what should I do when I want a copy of an object?
Depends on the context. In your case here, you'd probably take one of a few possible approaches:
1. Use a record for
TokenContext
, it probably should be one anyways. Then you wouldn't reassign individual properties like you're doing there, you'd with
to do non-destructive mutation
2. Use a builder for TokenContext
s. That's effectively what you're doing here, you're treating TokenContext
as if it was a builder. But combining these two things into one isn't great; you've opened yourself up to bugs because TokenContext
is mutable.
3. You could certainly make TokenContext
a struct
here. It's not the worst idea, given that there's only 5 pieces of data and they can presumably be enregistered by the JIT.
In any of these options, though, I would absolutely make TokenContext
immutable. After you create a Token
, there's almost certainly no reason to permit modification of TokenContext
welp, I'm well out my depth here. I'll probably just use struct since it makes the most sense to me, even if it isn't the most performant
I'm interested to know what I should be using for
Token
thoNearly certainly
class
But I would say you're coding very much like this is C++, not C#
We don't do public fields in C#, we use properties, so that we abstract whether things are actually fieldsnot sure what that means
Do you know what properties are?
nope
Alright. So, my suggestion is to do a few intro to C# things
Clearly, you know about programming, so you don't need the hello world, I've never seen a line of code in my life
But you should really learn about the basic building blocks of C#, like "what is a class", "what is a property", etc
Take a look through some of the articles here: https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/overview
Overview - A tour of C#
New to C#? Learn the basics of the language. Start with this overview.
yup, this is OOP hell
Being perfectly honest: if that's your first reaction, why are you using C#?
C# is a multiparadigm language, but types are at its core.
because I need cross platform support
and while my c++ code would probably work on mostly any system, compiling it would be a pain
it's not that bad
Unknown User•3d ago
Message Not Public
Sign In & Join Server To View