简体   繁体   中英

C#'s readonly vs C++'s const - Equivalents

This is mostly an understanding check, as I couldn't find a complete reference on this topic.

In C#, when I write readonly Foo myFoo , I'm essentially saying myFoo is a pointer to Foo , and the pointer cannot be reassigned. To guarantee that the underlying Foo can't be reassigned, I need a whole other class or interface ImmutableFoo .

Now consider the construct List<Foo> . It's basically a pointer to a list of pointers to Foo , ie similar to vector<Foo *> * in C++. There are three places where you could put const in C++.

const vector<const Foo *> * const
  • const #1: You cannot modify the vector (by resizing, reassigning elements, etc.)
  • const #2: You cannot modify the Foo-s pointed to inside the vector
  • const #3: You cannot modify the pointer to the vector

So I think the equivalent of each of these is,

List<Foo>               = vector<Foo *> *             // No consts
ReadOnlyCollection<Foo> = const vector<Foo *> *       // First const toggled
List<ImmutableFoo>      = vector<const Foo *> *       // Second const toggled
readonly List<Foo>      = vector<Foo *> * const       // Third const toggled

readonly ReadOnlyCollection<ImmutableFoo>
                        = const vector<const Foo *> * const // All consts toggled

Is this table of equivalencies correct?

Yes, I think you got it. I think this const to readonly translation is correct, even if you should not compare those two keywords . I think there are many other subtly and differently behaves between the C++ const and C# readonly keyword. Some of them are:

  • Const in C++ is more powerful, note that this keyword means a couple of different things in different contexts. In many situations using const in C++ is some kind of best practice. In C# we do not use the immutable paradigm that much, but the trend is showing up, if you take a look at the C# Immutable Collections .
  • In C# readonly is not really immutable, as you can still change readonly Fields/Properties by reflection .

tbc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM