2

I need to check for a certain version in one of my components. For that reason I just wanted to introduce a public const int on which I could test.

However, I just read in this SO post When, if ever, should we use const? that it's probably a bad idea to use a const whenever something changes in the future.

What's the best way to do that? Using a public readonly int? Using an attribute? I can't use AssemblyVersion or AssemblyFileVersion as those are not in my hand...

Thanks!

Community
  • 1
  • 1
Dunken
  • 8,481
  • 7
  • 54
  • 87
  • `those are not in my hand`, I'm sorry, what exactly do you mean by that? – Mike Perrenoud Sep 12 '12 at 11:30
  • Can you explain why you can't use AssemblyVersion etc. that is what they are for, surely if you are releasing a new version of an assembly then you can control this. – Ben Robinson Sep 12 '12 at 11:30
  • I might be reading more into it than what is actually there, but when I read the OP's post, I get the sense that his components are being used by others in their assemblies. However, to play together well, his components need the ability to check for compatability. If I'm right, I agree with Bart below and don't see a problem with using a const for this purpose. – Kevin Sep 12 '12 at 11:44
  • AssemblyVersion is assigned globally. I don't know the value of the AssemblyVersion. Therefore I don't know what versions are compatible. – Dunken Sep 12 '12 at 11:48
  • @Kevin: You're absolutely right. It's just that when I read the other SO post I got the impression that if I increase my const and exchange my dll other assemblies might still use the old const value... – Dunken Sep 12 '12 at 11:56

1 Answers1

3

I'd use the const (in fact, I do use it for that). readonly is initialised at run-time, in fact, it can have a different value every time you run the application [1]. Because of that propery, I'd say it is less useful for a version number.

A version number is (should be?) hard-coded at compile time, which would be a const. Comparison could be a #define in C.

I reckon that because of this difference, a const doesn't use data memory, as a readonly does. I have no sources for that though.

[1] http://en.csharp-online.net/const,_static_and_readonly

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • `readonly` doesn't have to be static, hence the memory used differs from `const` (which acts just like static fields with regard to memory). – Bartosz Sep 12 '12 at 12:07
  • It's just that when I read the other SO post I got the impression that if I increase my const and exchange my dll other assemblies might still use the old const value... – Dunken Sep 12 '12 at 12:16
  • @Dunken, I don't know if that would be the case. But it'd be easy to test. – Bart Friederichs Sep 12 '12 at 12:26