473,320 Members | 1,953 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Constant arrays in C#

Whats the reasoning for not being able to instantiate const arrays in
C# or have I missed something

void Foo()
{
const int i = 0;
const string str = "s";

// error CS0133: The expression being assigned to 'intArray' must be
constant
const int[] intArray = { 1,2,3 };
const string[] strArray = { "1","2","3" };
}

My solutin which isn't as elegant is to use at class scope
static readonly string[] _strArray = { "1","2","3" };

I can't reinitialize the array but _strArray[0] will change the
contents.

This is easy enough to do in C++ eg.

Regards
/m
Nov 15 '05 #1
11 21844
On 11/6/2003 10:40 AM, Michel Andr? wrote:
Whats the reasoning for not being able to instantiate const arrays in
C# or have I missed something

void Foo()
{
const int i = 0;
const string str = "s";

// error CS0133: The expression being assigned to 'intArray' must be
constant
const int[] intArray = { 1,2,3 };
const string[] strArray = { "1","2","3" };
}

My solutin which isn't as elegant is to use at class scope
static readonly string[] _strArray = { "1","2","3" };

I can't reinitialize the array but _strArray[0] will change the
contents.


From MSDN:

"A constant expression is an expression that can be fully evaluated at
compile time. Therefore, the only possible values for constants of
reference types are string and null."

Nov 15 '05 #2
Bogdan Lachendro <la***@no-spam.icslab.agh.edu.pl> wrote in message news:<uf**************@TK2MSFTNGP09.phx.gbl>...
From MSDN:

"A constant expression is an expression that can be fully evaluated at
compile time. Therefore, the only possible values for constants of
reference types are string and null."


I realize this and read it to. I just cant understand it since
constant objects come in quite handy often, both since they cannot be
misstakenly change and their construction can be obtimized, compiled
beforehand. But I guess it's my C++ mindset shining trough ;). I
actually miss const methods and objects as well, since the only way of
knowing noone will tinker with an objects state that I own is cloning
just in case somebody might change the state or depend that the user
clones the object if they change the state and how can they know what
state changes if that isn't marked (another of those C++ isms i miss).

/Michel
Nov 15 '05 #3
This refers to reference types. They are different from value types. Please
check
http://msdn.microsoft.com/library/de...harpspec_4.asp

and following sections. They explain the difference.

If you want to monitor for changes in referenced objects, I think properties
can help you to avoid cloning. You can always monitor where from call
originates and use declarative or security on methods. I would suggest to
check
http://msdn.microsoft.com/library/de...sssecurity.asp

As about const methods, possibly you should take a look at static methods /
properties. If I remember properly what is const method ;-))

HTH
Alex
"Michel Andr?" <mi**********@swipnet.se> wrote in message
news:3f**************************@posting.google.c om...
Bogdan Lachendro <la***@no-spam.icslab.agh.edu.pl> wrote in message

news:<uf**************@TK2MSFTNGP09.phx.gbl>...
From MSDN:

"A constant expression is an expression that can be fully evaluated at
compile time. Therefore, the only possible values for constants of
reference types are string and null."


I realize this and read it to. I just cant understand it since
constant objects come in quite handy often, both since they cannot be
misstakenly change and their construction can be obtimized, compiled
beforehand. But I guess it's my C++ mindset shining trough ;). I
actually miss const methods and objects as well, since the only way of
knowing noone will tinker with an objects state that I own is cloning
just in case somebody might change the state or depend that the user
clones the object if they change the state and how can they know what
state changes if that isn't marked (another of those C++ isms i miss).

/Michel

Nov 15 '05 #4
> This refers to reference types. They are different from value types. Please
check
http://msdn.microsoft.com/library/de...harpspec_4.asp

and following sections. They explain the difference.
I know the difference between a value type and a reference type. In
C++ it can be implemented more effiecient than in C# .NET CLR type
languages. And you don't have to sacrifice the one for the other at
design time as you have in C# where you choose value and ref by
interchanging struct and class. In C++ you have to decide if you want
an value or ref class, if you implement a value class by
implementening assignment,copy and destructory correctly you still can
pass the class by reference in a function call or return and then
decide at the caller site if you want to clone the value (calling a
non const function) or just "read" state. In C# and managed C++ you
decide up front as I understand it.
If you want to monitor for changes in referenced objects, I think properties
can help you to avoid cloning. You can always monitor where from call
originates and use declarative or security on methods. I would suggest to
check
http://msdn.microsoft.com/library/de...sssecurity.asp
Using properties is a runtime check incurring runtime overhead and
failures, const correctnes can be verified at compile time in C++ and
makes it a lot faster than a runtime check each time you access the
property/method.

As about const methods, possibly you should take a look at static methods /
properties. If I remember properly what is const method ;-))


Static methods and const methods are not the same. A const method in
C++ can't change the state of an object but can read the state and
calculate return values and such from the state. And a static method
don't have access to the state of an object neither in C++ or C# they
are the same.

/Regards
Michel
Nov 15 '05 #5
Well you could wrap a reference with private visiblility in a class and
provide only read only methods.... or pass immutable objects.

Regards,
Jeff
I actually miss const methods and objects as well, since the only way

of
knowing noone will tinker with an objects state that I own is cloning
just in case somebody might change the state or depend that the user
clones the object if they change the state and how can they know what
state changes if that isn't marked (another of those C++ isms i miss).<
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #6
Michel Andr? <mi**********@swipnet.se> wrote:
If you want to monitor for changes in referenced objects, I think properties
can help you to avoid cloning. You can always monitor where from call
originates and use declarative or security on methods. I would suggest to
check
http://msdn.microsoft.com/library/de...s/cpguide/html
/cpconcodeaccesssecurity.asp


Using properties is a runtime check incurring runtime overhead and
failures, const correctnes can be verified at compile time in C++ and
makes it a lot faster than a runtime check each time you access the
property/method.


Properties don't always involve a runtime overhead at all - usually
they'll be inlined into the same native code, especially if they're
very simple ones.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #7
Jeff Louie <je********@yahoo.com> wrote in message news:<OL**************@TK2MSFTNGP10.phx.gbl>...
Well you could wrap a reference with private visiblility in a class and
provide only read only methods.... or pass immutable objects.


How do you pass immutable objects? Or do you mean implementing a class
wrapper with readonly access. It means duplicating code but I think it
would work.

/Michel
Nov 15 '05 #8
Jon Skeet [C# MVP] <sk***@pobox.com> wrote in message news:<MP************************@msnews.microsoft. com>...
Michel Andr? <mi**********@swipnet.se> wrote:
If you want to monitor for changes in referenced objects, I think properties
can help you to avoid cloning. You can always monitor where from call
originates and use declarative or security on methods. I would suggest to
check
http://msdn.microsoft.com/library/de...s/cpguide/html
/cpconcodeaccesssecurity.asp


Using properties is a runtime check incurring runtime overhead and
failures, const correctnes can be verified at compile time in C++ and
makes it a lot faster than a runtime check each time you access the
property/method.


Properties don't always involve a runtime overhead at all - usually
they'll be inlined into the same native code, especially if they're
very simple ones.


But according to the reply I should use declarative code security and
monitor where calls come from and these checks must certainly be done
at runtime and incur an overhead. And adding declarative properties to
property accessor or making more advanced setters will make the chance
of inlining smaller.

/Michel
Nov 15 '05 #9
Hi Michel.... A class wrapper with read only access is one way to go, so
called "containment by reference".

http://www.geocities.com/jeff_louie/OOP/oop7.htm

The use of immutable objects requires a different approach to
programming. Most of use like to reuse code in memory so we write
mutable classes. This may not be the best approach in C# or Java. A
reference is "Effective Java" by Guy Steele Item 13 "Favor
Immutability."

So if you have a class that performs a complex calculation, that class
can
provide a method that returns an immutable result object (no getters) or
in C# a user defined structure.

http://www.geocities.com/jeff_louie/OOP/oop11.htm

Regards,
Jeff
How do you pass immutable objects? Or do you mean implementing a

class wrapper with readonly access. It means duplicating code but I
think
it would work.<
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #10
Argh. Methinks I mean no setters.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #11
Michel Andr? <mi**********@swipnet.se> wrote:
Properties don't always involve a runtime overhead at all - usually
they'll be inlined into the same native code, especially if they're
very simple ones.
But according to the reply I should use declarative code security and
monitor where calls come from and these checks must certainly be done
at runtime and incur an overhead.


No, the reply said you *could* do that if you needed to, not that you
*do* need to.
And adding declarative properties to
property accessor or making more advanced setters will make the chance
of inlining smaller.


Yup - but for the most part, just adding the property would be enough
to give read-only access.

I agree that it's a problem, and I would like some way of letting the
compiler know that an array itself should be viewed as being readonly
rather than just the reference - I was merely trying to get away from
the idea that having a property always made things slower.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: richbl | last post by:
Hello all, I have a question about unserializing a single array element from a serialized array. Can this be done, or must I first unserialize the array, and then access the element? For...
6
by: Lionel B | last post by:
Running VC++ 6 under Win2K on i386. I would like to assign a (compile-time) constant that resolves to a quiet NaN (of type double) I can assign a quiet NaN to a *variable* (of type const...
9
by: xtra | last post by:
Hi Folk Is it possible to declare a constant array e.g. dim i() as string i(1) = ... i(2) = ... seems to work but the following does not const i(1) = ....
10
by: Ricardo Gibert | last post by:
How can I "force" a macro to accept integer constants or expressions whose value is determined during compilation? For example, if we have: #define TEST(X) blah blah with X I want the macro to...
2
by: JJ Feminella | last post by:
This statement is legal C#: public const string day = "Sunday"; but this statement is not: public const string days = new string { "Sun", "Mon", "Tue" }; The C# Programmer's Reference...
25
by: galapogos | last post by:
Hi, I'm trying to compare an array of unsigned chars(basically just data without any context) with a constant, and I'm not sure how to do that. Say my array is array and I want to compare it with...
4
by: Quentin Yuan | last post by:
I always consider that the constant character strings of which literal value are the same lay out at the same logic address, in another words, every constant character string have only one copy in...
5
by: =?Utf-8?B?UnlhbiBBbmRydXM=?= | last post by:
Is there a way to configure\create a datatable (strongly typed or untyped) that can have a row accessed in constant time if you are searching on the primary key? If there isn't a way, then what...
13
by: Szabolcs | last post by:
Is the following legal? void fun(int N) { int arr; } gcc and Digital Mars accept it, but msvc complains that it wants a constant expression.
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.