Constant arrays in C#

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Michel Andr?

    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
  • Bogdan Lachendro

    #2
    Re: Constant arrays in C#

    On 11/6/2003 10:40 AM, Michel Andr? wrote:[color=blue]
    > 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.[/color]

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

    Comment

    • Michel Andr?

      #3
      Re: Constant arrays in C#

      Bogdan Lachendro <lachu@no-spam.icslab.agh .edu.pl> wrote in message news:<ufohp1EpD HA.1676@TK2MSFT NGP09.phx.gbl>. ..[color=blue]
      > 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."[/color]

      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

      Comment

      • AlexS

        #4
        Re: Constant arrays in C#

        This refers to reference types. They are different from value types. Please
        check


        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


        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?" <michel.andre@s wipnet.se> wrote in message
        news:3f4f8c0a.0 311071143.38ef5 1eb@posting.goo gle.com...[color=blue]
        > Bogdan Lachendro <lachu@no-spam.icslab.agh .edu.pl> wrote in message[/color]
        news:<ufohp1EpD HA.1676@TK2MSFT NGP09.phx.gbl>. ..[color=blue][color=green]
        > > 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."[/color]
        >
        > 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[/color]


        Comment

        • Michel Andr?

          #5
          Re: Constant arrays in C#

          > This refers to reference types. They are different from value types. Please[color=blue]
          > check
          > http://msdn.microsoft.com/library/de...harpspec_4.asp
          >
          > and following sections. They explain the difference.[/color]

          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.
          [color=blue]
          > 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[/color]

          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.
          [color=blue]
          >
          > As about const methods, possibly you should take a look at static methods /
          > properties. If I remember properly what is const method ;-))
          >[/color]

          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

          Comment

          • Jeff Louie

            #6
            Re: Constant arrays in C#

            Well you could wrap a reference with private visiblility in a class and
            provide only read only methods.... or pass immutable objects.

            Regards,
            Jeff[color=blue]
            >I actually miss const methods and objects as well, since the only way[/color]
            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!

            Comment

            • Jon Skeet [C# MVP]

              #7
              Re: Constant arrays in C#

              Michel Andr? <michel.andre@s wipnet.se> wrote:[color=blue][color=green]
              > > 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
              > > /cpconcodeaccess security.asp[/color]
              >
              > 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.[/color]

              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 - <skeet@pobox.co m>
              Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

              If replying to the group, please do not mail me too

              Comment

              • Michel Andr?

                #8
                Re: Constant arrays in C#

                Jeff Louie <jeff_louie@yah oo.com> wrote in message news:<OLTFJQnpD HA.1680@TK2MSFT NGP10.phx.gbl>. ..[color=blue]
                > Well you could wrap a reference with private visiblility in a class and
                > provide only read only methods.... or pass immutable objects.
                >[/color]

                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

                Comment

                • Michel Andr?

                  #9
                  Re: Constant arrays in C#

                  Jon Skeet [C# MVP] <skeet@pobox.co m> wrote in message news:<MPG.1a180 c45dfc9bd9b989a 52@msnews.micro soft.com>...[color=blue]
                  > Michel Andr? <michel.andre@s wipnet.se> wrote:[color=green][color=darkred]
                  > > > 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
                  > > > /cpconcodeaccess security.asp[/color]
                  > >
                  > > 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.[/color]
                  >
                  > 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.[/color]

                  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

                  Comment

                  • Jeff Louie

                    #10
                    Re: Constant arrays in C#

                    Hi Michel.... A class wrapper with read only access is one way to go, so
                    called "containmen t by reference".

                    Latest news coverage, email, free stock quotes, live scores and video are just the beginning. Discover more every day at Yahoo!


                    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.

                    Latest news coverage, email, free stock quotes, live scores and video are just the beginning. Discover more every day at Yahoo!


                    Regards,
                    Jeff[color=blue]
                    >How do you pass immutable objects? Or do you mean implementing a[/color]
                    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!

                    Comment

                    • Jeff Louie

                      #11
                      Re: Constant arrays in C#

                      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!

                      Comment

                      • Jon Skeet [C# MVP]

                        #12
                        Re: Constant arrays in C#

                        Michel Andr? <michel.andre@s wipnet.se> wrote:[color=blue][color=green]
                        > > 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.[/color]
                        >
                        > 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.[/color]

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

                        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 - <skeet@pobox.co m>
                        Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                        If replying to the group, please do not mail me too

                        Comment

                        Working...