|
-
September 1st, 2011, 05:52 PM
#1
declaring a const object in C#
Folks,
I used to be an enthusiastic C++ writer. Currently, I’m going up the learning curve of .NET and C#.
From what I’m reading on the web, only the C# built-in types may be declared as const. Is there a workaround that would allow to declare a constant local object variable, an instance of a framework class?
Code:
private void foo()
{
const Size sz = new Size(19, 16); // this doesn’t work in C#
// ...
}
Any suggestion, insight or reference is really appreciated!
- Nick
P.S. It would be lamentable, if designers of C# just decided not to implement the const facilities of C++ (which were well thought through, IMHO).
Last edited by kender_a; September 1st, 2011 at 07:41 PM.
-
September 1st, 2011, 06:34 PM
#2
Re: declaring a const object in C#
Yes, because const objects need to be const at compile time. You need to declare it as readonly, which will also allow you to initialize it in a constructor if needed:
Code:
private readonly Size _sz = new Size( 19, 16 );
On a side note, I'm all for const-correctness in C++ as well, but as you can just cast it away it loses a lot of its utility if someone wants to get around it.
-
September 1st, 2011, 06:40 PM
#3
Re: declaring a const object in C#
Use the "static readonly" modifier.
True const-ness is impossible to enforce in C++, as you probably know from using it, so C# decided to not go down that rabbit hole. A smart move If you want a truly const object in C# just ensure it has no mutable state.
EDIT: beaten to it! Though to make up for it i'll add a nugget of info. Suppose you have a library which declares "public const int Version = 1;". If you reference that const field in code which uses that library, the value '1' will be compiled into that code. This means that if the library gets a bugfix and the developer of that library changes the version constant to '2', your code will not get that value unless you *recompile* your application. If the value was declared as 'static readonly' then this problem would not happen.
Essentially, if you change the value of a const property in C# this counts as an ABI/API breakage and you must bump the version numbers if you have a strong named assembly. People *must* recompile their applications against your library.
Last edited by Mutant_Fruit; September 1st, 2011 at 06:44 PM.
www.monotorrent.com For all your .NET bittorrent needs
NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.
-
September 1st, 2011, 08:04 PM
#4
Re: declaring a const object in C#
In addition, as long as you're coding style/design is in the realm of sane, the lack of a more fine-grained "constness control" as it appears in C++ is not really a problem.
In a way, it forces you to write better code, and better designed apps.
Basically, in OO, generally speaking, only the object itself should be allowed to change its own internal state - which means that an instance method must be called. Simply don't call any methods that mutate (change the internal state of) the object. If such an operation is required locally, consider making a copy, to simulate pass-by-value semantics for reference types (but beware of shallow copies). Value types (structs, built-in numeric types) are passed by value by default.
Finally, you can create types that are immutable by design (an approach that often has many benefits, like thread safety). The strings you use all the time in C# are instances of an immutable System.String class.
This maybe sounds a bit too complicated, but in practice, you don't really need to think about all that stuff all the time.
The reason I decided to post here is because I have a few remarks on the readonly keyword.
In C#, reference types are implemented via some kind of a reference-counting / smart pointer-like thing we call a reference, but the exact nature of this thing is a language implementation detail, and it's not relevant to us.
What is relevant is its semantics: it references an object instance - it's a means to obtain and manipulate the object it "points to", the same way a street address is a reference to a house.
Now, the readonly keyword only specifies that the reference to the object cannot be changed, not the object itself. So, unless the object in question is of an immutable type, you can change its internal state all you like.
What you can't do is assign a different instance to the same variable.
In C#, you'll mostly create/deal with reference types, and only occasionally with value types (excluding all the ints, floats, doubles, bools and such that popup everywhere).
Nevertheless, it's important to understand the difference between the two.
If you're interested in finding out more, see this thread - it talks about value types, reference types, about how strings are immutable and what that means, and has a few words about all the ways objects are passed around.
Last edited by TheGreatCthulhu; September 1st, 2011 at 08:08 PM.
-
September 2nd, 2011, 02:14 PM
#5
Re: declaring a const object in C#
Well, immutable state is really more of a functional paradigm than OO and is a luadable goal, but immutability doesn't always model the real world well and you can't always get away with it in a C# app.
-
September 2nd, 2011, 05:06 PM
#6
Re: declaring a const object in C#
 Originally Posted by BigEd781
Well, immutable state is really more of a functional paradigm than OO [...]
I never said it's an OO concept.
 Originally Posted by BigEd781
[... ]immutable state [...] is a luadable goal, but immutability doesn't always model the real world well and you can't always get away with it in a C# app.
I didn't say you can - I just named it as an option, and discussed how the readonly keyword affects mutable and immutable types.

Hehe, sorry about that... the smiley feels so smugly...
Anyway, good that you brought this up, since if you interpreted my last post to mean that, so can the OP, and that's definitively something to be avoided if possible.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|