Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c#

constants

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, i.e. 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?

like image 895
jcai Avatar asked Aug 11 '15 15:08

jcai


1 Answers

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...

like image 156
David Leitner Avatar answered Sep 18 '22 22:09

David Leitner