I come from C++ and find a very different behavior between pointers in C++ and C#.
I surprisingly find this code compiles... And even... Works perfectly.
class C
{
private readonly int x = 0;
unsafe public void Edit()
{
fixed (int* p = &x)
{
*p = x + 1;
}
Console.WriteLine($"Value: {x}");
}
}
This make me very puzzled, even in C++ we have a mechanism to protect const
objects(const
in C++ almost the same thing as readonly
in C#, not const
in C#), because we don't have enough reason to arbitrarily modify const values through pointers.
Exploring further, I find there's no equivalent to C++'s low level const pointers in C#, which will be something like:
readonly int* p
in C# if it had one.
Then p can only read the object pointed to, and cannot write to it.
And for const
objects, C# banned the attempts to retrieve their address.
In C++, any attempt to modify the const
is either compile error or Undefined Behavior. In C#, I don't know whether there is any possibility that we can make use of this.
So my question is:
- Is this behavior really well-defined? Though I know in C# there's no concept like UB in C++
- If so, how should I use it? Or never use it?
Note: In comment section: casting away const
in C++ is not related to this question, because It's valid only when the pointed to object itself is not const
, otherwise it's UB. Plus, I'm basically talking about C# and compile time behavior.
You can ask me to provide more details if you don't fully understand the question. I found most of people cannot understand this correctly, maybe it's my fault not making it clear.