Unassigned variables Confusion

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rene

    Unassigned variables Confusion

    I understand that if I don't assign a *local* variable before I use it, the
    compiler will generate a "Use of unassigned local variable" error. What I
    don't get is why doesn't the compiler just implicitly assign a default value
    to my unassigned variable?

    At this point you are getting ready to reply to me and tell me that this is
    just a way for the compiler to protect me from introducing a possible bug by
    preventing me from forgetting to assign the value. The problem is that if
    that was true, why doesn't it do the same thing for field level variables? I
    mean, surely I could screw up there too right?

    I have been scouring the web for a good answer and I have been unlucky in
    finding a good response. Thank you for you time.


  • Rakesh Rajan

    #2
    RE: Unassigned variables Confusion

    Hi Rene,

    Field level variables will be initialized to default values when the
    instance is contructed. Since the compiler takes care of this, you don't have
    to explicitly assign the values.

    HTH,
    Rakesh Rajan

    "Rene" wrote:
    [color=blue]
    > I understand that if I don't assign a *local* variable before I use it, the
    > compiler will generate a "Use of unassigned local variable" error. What I
    > don't get is why doesn't the compiler just implicitly assign a default value
    > to my unassigned variable?
    >
    > At this point you are getting ready to reply to me and tell me that this is
    > just a way for the compiler to protect me from introducing a possible bug by
    > preventing me from forgetting to assign the value. The problem is that if
    > that was true, why doesn't it do the same thing for field level variables? I
    > mean, surely I could screw up there too right?
    >
    > I have been scouring the web for a good answer and I have been unlucky in
    > finding a good response. Thank you for you time.
    >
    >
    >[/color]

    Comment

    • Rene

      #3
      Re: Unassigned variables Confusion

      So why doesn't the compiler do the same thing for the local variables?

      "Rakesh Rajan" <RakeshRajan@di scussions.micro soft.com> wrote in message
      news:D75A6AAD-5458-43B8-B727-620A0054906F@mi crosoft.com...[color=blue]
      > Hi Rene,
      >
      > Field level variables will be initialized to default values when the
      > instance is contructed. Since the compiler takes care of this, you don't
      > have
      > to explicitly assign the values.
      >
      > HTH,
      > Rakesh Rajan
      >
      > "Rene" wrote:
      >[color=green]
      >> I understand that if I don't assign a *local* variable before I use it,
      >> the
      >> compiler will generate a "Use of unassigned local variable" error. What I
      >> don't get is why doesn't the compiler just implicitly assign a default
      >> value
      >> to my unassigned variable?
      >>
      >> At this point you are getting ready to reply to me and tell me that this
      >> is
      >> just a way for the compiler to protect me from introducing a possible bug
      >> by
      >> preventing me from forgetting to assign the value. The problem is that if
      >> that was true, why doesn't it do the same thing for field level
      >> variables? I
      >> mean, surely I could screw up there too right?
      >>
      >> I have been scouring the web for a good answer and I have been unlucky in
      >> finding a good response. Thank you for you time.
      >>
      >>
      >>[/color][/color]


      Comment

      • Rakesh Rajan

        #4
        Re: Unassigned variables Confusion

        Hi Rene,

        Look at it like this:
        You declare a local variable only when you are going to make any practical
        use of the value it contains.
        If the compiler had been setting default values for local variables as well,
        they will either be set to null (for classes) etc., which will surely throw
        an error as soon as you try to access it's members.

        Hence, to make sure that you yourself initialize the local var's, we have
        this design.

        HTH,
        Rakesh Rajan

        "Rene" wrote:
        [color=blue]
        > So why doesn't the compiler do the same thing for the local variables?
        >
        > "Rakesh Rajan" <RakeshRajan@di scussions.micro soft.com> wrote in message
        > news:D75A6AAD-5458-43B8-B727-620A0054906F@mi crosoft.com...[color=green]
        > > Hi Rene,
        > >
        > > Field level variables will be initialized to default values when the
        > > instance is contructed. Since the compiler takes care of this, you don't
        > > have
        > > to explicitly assign the values.
        > >
        > > HTH,
        > > Rakesh Rajan
        > >
        > > "Rene" wrote:
        > >[color=darkred]
        > >> I understand that if I don't assign a *local* variable before I use it,
        > >> the
        > >> compiler will generate a "Use of unassigned local variable" error. What I
        > >> don't get is why doesn't the compiler just implicitly assign a default
        > >> value
        > >> to my unassigned variable?
        > >>
        > >> At this point you are getting ready to reply to me and tell me that this
        > >> is
        > >> just a way for the compiler to protect me from introducing a possible bug
        > >> by
        > >> preventing me from forgetting to assign the value. The problem is that if
        > >> that was true, why doesn't it do the same thing for field level
        > >> variables? I
        > >> mean, surely I could screw up there too right?
        > >>
        > >> I have been scouring the web for a good answer and I have been unlucky in
        > >> finding a good response. Thank you for you time.
        > >>
        > >>
        > >>[/color][/color]
        >
        >
        >[/color]

        Comment

        • Richard Blewett [DevelopMentor]

          #5
          Re: Unassigned variables Confusion

          In fact the compiler does already initialize local variables to 0 or null (see the .locals init in the IL). But the C# compiler is being extra cautious and requesting you be explicit to how you want them initialized. And yes, it is inconsistent with how it treats member variables.

          However, for statics, for example, the IL produced if you use a static field initializer is different form if you don't and there are performance optimizations based on this. So I think in terms of member variables they decided to be consistent within instance and statics and keep a then strict view on locals making people explicitly initialize them. This was, of course, consistent with best practice from C++ (the grandfather of C#) where locals would be garbage unless you initialized them.

          Regards

          Richard Blewett - DevelopMentor



          nntp://news.microsoft. com/microsoft.publi c.dotnet.langua ges.csharp/<66C1A5E9-D48D-4AB5-B6DD-6F861EAA3F3F@mi crosoft.com>

          Hi Rene,

          Look at it like this:
          You declare a local variable only when you are going to make any practical
          use of the value it contains.
          If the compiler had been setting default values for local variables as well,
          they will either be set to null (for classes) etc., which will surely throw
          an error as soon as you try to access it's members.

          Hence, to make sure that you yourself initialize the local var's, we have
          this design.

          HTH,
          Rakesh Rajan

          Comment

          • Jon Skeet [C# MVP]

            #6
            Re: Unassigned variables Confusion

            Rene <nospam@nospam. nospam> wrote:[color=blue]
            > I understand that if I don't assign a *local* variable before I use it, the
            > compiler will generate a "Use of unassigned local variable" error. What I
            > don't get is why doesn't the compiler just implicitly assign a default value
            > to my unassigned variable?
            >
            > At this point you are getting ready to reply to me and tell me that this is
            > just a way for the compiler to protect me from introducing a possible bug by
            > preventing me from forgetting to assign the value. The problem is that if
            > that was true, why doesn't it do the same thing for field level variables? I
            > mean, surely I could screw up there too right?[/color]

            Yes, but you basically *can't* protect yourself against that. If you've
            got two methods, one of which sets a variable and the other of which
            returns it, how would you expect the compiler to know in what order
            those methods are called by other classes?

            It's not that the compiler is doing the wrong thing with local
            variables - it's that it doesn't have enough information to do the
            right thing with static/instance variables.

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

            • Rene

              #7
              Re: Unassigned variables Confusion

              Well, I am still unclear on the issue. The only reason why I would declare a
              field level variable is because I also have intentions to use it, otherwise
              why would I bother?



              Having said that, the compiler should enforce the same rules as the one
              found for the Local variables! I don't get it!!!
              [color=blue]
              > Look at it like this:
              > You declare a local variable only when you are going to make any practical
              > use of the value it contains.
              > If the compiler had been setting default values for local variables as
              > well,
              > they will either be set to null (for classes) etc., which will surely
              > throw
              > an error as soon as you try to access it's members.[/color]


              Comment

              • Rakesh Rajan

                #8
                Re: Unassigned variables Confusion

                Exactly...and because you are going to use it, it should be ensures that you
                set a value to it before it is accessed.

                public void MyMethod()
                {
                Class1 obj;
                Console.WriteLi ne(obj.Property 1); // This would cause an error
                }

                HTH,
                Rakesh Rajan

                "Rene" wrote:
                [color=blue]
                > Well, I am still unclear on the issue. The only reason why I would declare a
                > field level variable is because I also have intentions to use it, otherwise
                > why would I bother?
                >
                >
                >
                > Having said that, the compiler should enforce the same rules as the one
                > found for the Local variables! I don't get it!!!
                >[color=green]
                > > Look at it like this:
                > > You declare a local variable only when you are going to make any practical
                > > use of the value it contains.
                > > If the compiler had been setting default values for local variables as
                > > well,
                > > they will either be set to null (for classes) etc., which will surely
                > > throw
                > > an error as soon as you try to access it's members.[/color]
                >
                >
                >[/color]

                Comment

                • Rene

                  #9
                  Re: Unassigned variables Confusion

                  Ok, I get it now. If by some magical way the compiler could know that I
                  would be calling the "get" method first, the compiler could raise an error
                  to let me know that I am about to do something stupid and I should call the
                  "set" method first. Boy, I feel like such as dumb ass. (Jon, you definitely
                  have enlightened me several times now, how could I ever repay you??)



                  Thank you all.



                  PS: Richard, thanks for pointing out the ILDASM stuff. I will check it out
                  as soon as I get a chance.


                  "Jon Skeet [C# MVP]" <skeet@pobox.co m> wrote in message
                  news:MPG.1bf93d 8a75e7d9bb98b89 3@msnews.micros oft.com...[color=blue]
                  > Rene <nospam@nospam. nospam> wrote:[color=green]
                  >> I understand that if I don't assign a *local* variable before I use it,
                  >> the
                  >> compiler will generate a "Use of unassigned local variable" error. What I
                  >> don't get is why doesn't the compiler just implicitly assign a default
                  >> value
                  >> to my unassigned variable?
                  >>
                  >> At this point you are getting ready to reply to me and tell me that this
                  >> is
                  >> just a way for the compiler to protect me from introducing a possible bug
                  >> by
                  >> preventing me from forgetting to assign the value. The problem is that if
                  >> that was true, why doesn't it do the same thing for field level
                  >> variables? I
                  >> mean, surely I could screw up there too right?[/color]
                  >
                  > Yes, but you basically *can't* protect yourself against that. If you've
                  > got two methods, one of which sets a variable and the other of which
                  > returns it, how would you expect the compiler to know in what order
                  > those methods are called by other classes?
                  >
                  > It's not that the compiler is doing the wrong thing with local
                  > variables - it's that it doesn't have enough information to do the
                  > right thing with static/instance variables.
                  >
                  > --
                  > Jon Skeet - <skeet@pobox.co m>
                  > http://www.pobox.com/~skeet
                  > If replying to the group, please do not mail me too[/color]


                  Comment

                  • Richard Blewett [DevelopMentor]

                    #10
                    Re: Unassigned variables Confusion

                    Yes, but this is equally valid:

                    public void MyMethod()
                    {
                    Class1 obj = null;
                    Console.WriteLi ne(obj.Property 1);
                    }

                    And in fact the compiler will have already emitted the IL instruction to do the same as the first line of the method, so simply declaring the variable *could* be enough for everything to work in a defined way. The issue is why does the C# compiler force you to assign a *specific* value when it has already ensured that it will default to null (in this case).

                    To me the answer is that C# is all about the code being explicitly obvious by looking at it, not having to infer details from knowledge outside of what you are looking at. This is one of the benefits for example of have to use the ref keyword at a method call site as well as in the method definition (of course the other reason is that you can overload ref and non-ref versions of a method and it needs to be able to tell the difference in that case).

                    Regards

                    Richard Blewett - DevelopMentor



                    nntp://news.microsoft. com/microsoft.publi c.dotnet.langua ges.csharp/<0EEAD256-3547-4821-824A-E7B743F605C2@mi crosoft.com>

                    Exactly...and because you are going to use it, it should be ensures that you
                    set a value to it before it is accessed.

                    public void MyMethod()
                    {
                    Class1 obj;
                    Console.WriteLi ne(obj.Property 1); // This would cause an error
                    }

                    HTH,
                    Rakesh Rajan

                    Comment

                    • Rakesh Rajan

                      #11
                      Re: Unassigned variables Confusion

                      Hi Richard,

                      I agree with your point that assigning null to the variable is being
                      internally done by the IL, and is the same as leaving the variable without
                      initializing it.

                      But, what I had been trying to say is that, this won't eliminate the error
                      that will happen when you try to access an object that is uninitialized.

                      This could be overridden when you are forced to explicitly initialize a
                      variable.

                      - Rakesh Rajan

                      "Richard Blewett [DevelopMentor]" wrote:
                      [color=blue]
                      > Yes, but this is equally valid:
                      >
                      > public void MyMethod()
                      > {
                      > Class1 obj = null;
                      > Console.WriteLi ne(obj.Property 1);
                      > }
                      >
                      > And in fact the compiler will have already emitted the IL instruction to do the same as the first line of the method, so simply declaring the variable *could* be enough for everything to work in a defined way. The issue is why does the C# compiler force you to assign a *specific* value when it has already ensured that it will default to null (in this case).
                      >
                      > To me the answer is that C# is all about the code being explicitly obvious by looking at it, not having to infer details from knowledge outside of what you are looking at. This is one of the benefits for example of have to use the ref keyword at a method call site as well as in the method definition (of course the other reason is that you can overload ref and non-ref versions of a method and it needs to be able to tell the difference in that case).
                      >
                      > Regards
                      >
                      > Richard Blewett - DevelopMentor
                      > http://www.dotnetconsult.co.uk/weblog
                      > http://www.dotnetconsult.co.uk
                      >
                      > nntp://news.microsoft. com/microsoft.publi c.dotnet.langua ges.csharp/<0EEAD256-3547-4821-824A-E7B743F605C2@mi crosoft.com>
                      >
                      > Exactly...and because you are going to use it, it should be ensures that you
                      > set a value to it before it is accessed.
                      >
                      > public void MyMethod()
                      > {
                      > Class1 obj;
                      > Console.WriteLi ne(obj.Property 1); // This would cause an error
                      > }
                      >
                      > HTH,
                      > Rakesh Rajan
                      >
                      >[/color]

                      Comment

                      • Richard Blewett [DevelopMentor]

                        #12
                        Re: Unassigned variables Confusion

                        I agree that it forces you to think about how you want that variable initialized and its better in that respect to get a compile time error rather than a runtime one. I suppose the issue the OP was having is why aren't you forced to provide field initializers for member variables in that case

                        Regards

                        Richard Blewett - DevelopMentor



                        nntp://news.microsoft. com/microsoft.publi c.dotnet.langua ges.csharp/<0226794F-13C8-4454-93AE-9FF2A4DFD15F@mi crosoft.com>

                        Hi Richard,

                        I agree with your point that assigning null to the variable is being
                        internally done by the IL, and is the same as leaving the variable without
                        initializing it.

                        But, what I had been trying to say is that, this won't eliminate the error
                        that will happen when you try to access an object that is uninitialized.

                        This could be overridden when you are forced to explicitly initialize a
                        variable.

                        Comment

                        • C# Learner

                          #13
                          Re: Unassigned variables Confusion

                          Rene <nospam@nospam. nospam> wrote:
                          [color=blue]
                          > Jon, you definitely
                          > have enlightened me several times now, how could I ever repay you??[/color]

                          Imagine if every time Jon helped someone out on here, they gave him £1 --
                          he could be a millionaire by now! <g>

                          Comment

                          Working...