Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Why is this necessary?

Why is this necessary?

Scheduled Pinned Locked Moved C#
questioncsharp
30 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • B Offline
    B Offline
    Brian_TheLion
    wrote on last edited by
    #1

    One more question... In C# you have 'animal fox = new animal()' Why do you need to repeat the word animal? Why not have 'fox = new animal()' Brian

    OriginalGriffO Richard DeemingR 3 Replies Last reply
    0
    • B Brian_TheLion

      One more question... In C# you have 'animal fox = new animal()' Why do you need to repeat the word animal? Why not have 'fox = new animal()' Brian

      OriginalGriffO Offline
      OriginalGriffO Offline
      OriginalGriff
      wrote on last edited by
      #2

      So that C# "knows" what kind of objects can be put in it! Remember that a variable can contain an instance of the type it was declared as, plus any derived types. So is you have a class hierarchy:

      class Animal {}
      class Mammal : Animal {}
      class Birds : Animal {}
      class Fish : Animal {}
      class Reptiles : Animal {}
      class Amphibian : Animal {}
      class Fox : Mammal {}

      Then declaring createurs is legal:

      Fox fox = new Fox();

      And

      Mammal mammal = new Fox();

      And so is this:

      Bird eagle = new Eagle();

      And you can do this:

      Animal animal = fox;
      animal = eagle;
      animal = mammal;

      But you can't do this:

      eagle = fox;

      Or this:

      eagle = mammal;

      Or even:

      fox = eagle;

      Because they don't make any sense in a real world. Telling C# what type of object a variable can contain means it can catch errors at compile time instead of when your program is running, which makes your code both easier to read and more reliable.

      Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      B 1 Reply Last reply
      0
      • B Brian_TheLion

        One more question... In C# you have 'animal fox = new animal()' Why do you need to repeat the word animal? Why not have 'fox = new animal()' Brian

        OriginalGriffO Offline
        OriginalGriffO Offline
        OriginalGriff
        wrote on last edited by
        #3

        Now I've had some coffee, I'll add some thoughts for you. If you allowed

        fox = new animal();

        without the type specifier, what problems might it cause? Well, consider this:

        public animal fox { get; set; }
        public void DoSummat(animal a)
        {
        fox = a;
        ...
        }

        Is the fox assignment inside DoSummat meant to create a new local instance which is scoped to just the method, or to affect the public property? How could you tell? How could I tell when I tried to fix a problem in 100,000 lines of code next year? Worse, is fox supposed to be an animal, or a mammal, or a Canidae? Does it make a difference? Yes - it does. Because bird is a type of animal but a fox doesn't have a FlapWings method! So if you allow implicit typing, then the compiler has to assume the lowest common type in the hierarchy and that could mean that methods you expect to work just don't exist for that actual instance. And consider this:

        public void DoSummat(animal a)
        {
        fox = a;
        ...
        fax = b;
        ...
        }

        Isfax a new variable, or did I mistype fox? How would you tell? C# is a strongly typed language: which means that there is no implicit declarations, no automatic type changing (except where data won't be lost such as int to double for example), and heavy duty type checking - which makes your code more robust because it finds problems at compile time, instead of hoping you tested all the possible routes through the code and didn't leave a "bad type" in there.

        Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

        B B J 3 Replies Last reply
        0
        • B Brian_TheLion

          One more question... In C# you have 'animal fox = new animal()' Why do you need to repeat the word animal? Why not have 'fox = new animal()' Brian

          Richard DeemingR Offline
          Richard DeemingR Offline
          Richard Deeming
          wrote on last edited by
          #4

          For local variables, it's not necessary to repeat the type name: var - C# Reference | Microsoft Docs[^] Implicitly typed local variables - C# Programming Guide | Microsoft Docs[^] The following two lines produce identical IL:

          Animal fox = new Animal();
          var fox = new Animal();

          NB: You can't use var for fields, property types, method parameters, or return types. Why no var on fields? – Fabulous Adventures In Coding[^] There is a suggestion which would allow fields declared as: Animal fox = new();, but it hasn't been implemented yet: csharplang/target-typed-new.md at master · dotnet/csharplang · GitHub[^] NB2: Some people vehemently oppose any use of var beyond anonymous types. And it certainly can be overused - for example, var x = Foo(); would compile, but is not readable. But for a new expression, where the type is right next to the variable declaration, I don't see any problem with using var. NB3: To clarify, based on the responses: using var for new expressions is fine; you should generally avoid it for anything else.

          • var x = new SomeType(); is fine.
          • var x = SomeMethod(); is bad.

          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

          OriginalGriffO L B 4 Replies Last reply
          0
          • Richard DeemingR Richard Deeming

            For local variables, it's not necessary to repeat the type name: var - C# Reference | Microsoft Docs[^] Implicitly typed local variables - C# Programming Guide | Microsoft Docs[^] The following two lines produce identical IL:

            Animal fox = new Animal();
            var fox = new Animal();

            NB: You can't use var for fields, property types, method parameters, or return types. Why no var on fields? – Fabulous Adventures In Coding[^] There is a suggestion which would allow fields declared as: Animal fox = new();, but it hasn't been implemented yet: csharplang/target-typed-new.md at master · dotnet/csharplang · GitHub[^] NB2: Some people vehemently oppose any use of var beyond anonymous types. And it certainly can be overused - for example, var x = Foo(); would compile, but is not readable. But for a new expression, where the type is right next to the variable declaration, I don't see any problem with using var. NB3: To clarify, based on the responses: using var for new expressions is fine; you should generally avoid it for anything else.

            • var x = new SomeType(); is fine.
            • var x = SomeMethod(); is bad.

            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

            OriginalGriffO Offline
            OriginalGriffO Offline
            OriginalGriff
            wrote on last edited by
            #5

            Personally, I'd recommend that beginners avoid var until they get to Linq, just to make it more obvious to them exactly what they are doing. But at least it's less horrendous than misused dynamic ... :sigh:

            Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

            "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
            "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

            L 1 Reply Last reply
            0
            • Richard DeemingR Richard Deeming

              For local variables, it's not necessary to repeat the type name: var - C# Reference | Microsoft Docs[^] Implicitly typed local variables - C# Programming Guide | Microsoft Docs[^] The following two lines produce identical IL:

              Animal fox = new Animal();
              var fox = new Animal();

              NB: You can't use var for fields, property types, method parameters, or return types. Why no var on fields? – Fabulous Adventures In Coding[^] There is a suggestion which would allow fields declared as: Animal fox = new();, but it hasn't been implemented yet: csharplang/target-typed-new.md at master · dotnet/csharplang · GitHub[^] NB2: Some people vehemently oppose any use of var beyond anonymous types. And it certainly can be overused - for example, var x = Foo(); would compile, but is not readable. But for a new expression, where the type is right next to the variable declaration, I don't see any problem with using var. NB3: To clarify, based on the responses: using var for new expressions is fine; you should generally avoid it for anything else.

              • var x = new SomeType(); is fine.
              • var x = SomeMethod(); is bad.

              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              I agree with OriginalGriff. Telling newbies to use var probably means that they will never use proper types.

              Richard DeemingR L B 3 Replies Last reply
              0
              • L Lost User

                I agree with OriginalGriff. Telling newbies to use var probably means that they will never use proper types.

                Richard DeemingR Offline
                Richard DeemingR Offline
                Richard Deeming
                wrote on last edited by
                #7

                Which is why I added the note that it's best saved for new expressions. Bad: var x = Foo(); Good: var x = new Bar();


                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                L 1 Reply Last reply
                0
                • Richard DeemingR Richard Deeming

                  Which is why I added the note that it's best saved for new expressions. Bad: var x = Foo(); Good: var x = new Bar();


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #8

                  Richard Deeming wrote:

                  Which is why ...

                  In the forlorn hope that your advice will be properly listened to. :laugh:

                  Richard DeemingR 1 Reply Last reply
                  0
                  • OriginalGriffO OriginalGriff

                    Personally, I'd recommend that beginners avoid var until they get to Linq, just to make it more obvious to them exactly what they are doing. But at least it's less horrendous than misused dynamic ... :sigh:

                    Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                    L Offline
                    L Offline
                    Lost User
                    wrote on last edited by
                    #9

                    Use "var" to help "keep you coding" if you're not sure what type is returned. (Methods; LINQ). THEN, after intelli-sense has resolved the type, you can then "mouse over the var" and convert it to an explicit type ("quick action" refactor). Perfect for a student (and memory-poor me), IMO.

                    "(I) am amazed to see myself here rather than there ... now rather than then". ― Blaise Pascal

                    OriginalGriffO B 2 Replies Last reply
                    0
                    • L Lost User

                      I agree with OriginalGriff. Telling newbies to use var probably means that they will never use proper types.

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #10

                      var is a training wheel for newbs (and me).

                      "(I) am amazed to see myself here rather than there ... now rather than then". ― Blaise Pascal

                      1 Reply Last reply
                      0
                      • L Lost User

                        Richard Deeming wrote:

                        Which is why ...

                        In the forlorn hope that your advice will be properly listened to. :laugh:

                        Richard DeemingR Offline
                        Richard DeemingR Offline
                        Richard Deeming
                        wrote on last edited by
                        #11

                        There's a first time for everything. :-D


                        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                        "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                        1 Reply Last reply
                        0
                        • L Lost User

                          Use "var" to help "keep you coding" if you're not sure what type is returned. (Methods; LINQ). THEN, after intelli-sense has resolved the type, you can then "mouse over the var" and convert it to an explicit type ("quick action" refactor). Perfect for a student (and memory-poor me), IMO.

                          "(I) am amazed to see myself here rather than there ... now rather than then". ― Blaise Pascal

                          OriginalGriffO Offline
                          OriginalGriffO Offline
                          OriginalGriff
                          wrote on last edited by
                          #12

                          Until you get to Linq, you should have a good idea what type you are using - particularly when you are just starting. I think explicit typing helps beginners rather than confuses them when they suddenly find it "won't pass x to method y" and can't understand why not. But hey! I'm not going to start a flame war about it! :laugh:

                          Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                          "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                          "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                          L 2 Replies Last reply
                          0
                          • OriginalGriffO OriginalGriff

                            Until you get to Linq, you should have a good idea what type you are using - particularly when you are just starting. I think explicit typing helps beginners rather than confuses them when they suddenly find it "won't pass x to method y" and can't understand why not. But hey! I'm not going to start a flame war about it! :laugh:

                            Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                            L Offline
                            L Offline
                            Lost User
                            wrote on last edited by
                            #13

                            OriginalGriff wrote:

                            I'm not going to start a flame war

                            Oh come on, we need a bit of excitement sometimes.

                            1 Reply Last reply
                            0
                            • OriginalGriffO OriginalGriff

                              Until you get to Linq, you should have a good idea what type you are using - particularly when you are just starting. I think explicit typing helps beginners rather than confuses them when they suddenly find it "won't pass x to method y" and can't understand why not. But hey! I'm not going to start a flame war about it! :laugh:

                              Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                              L Offline
                              L Offline
                              Lost User
                              wrote on last edited by
                              #14

                              Reminds of "History" classes ... memorizing dates before they meant something. Different strokes.

                              "(I) am amazed to see myself here rather than there ... now rather than then". ― Blaise Pascal

                              1 Reply Last reply
                              0
                              • OriginalGriffO OriginalGriff

                                So that C# "knows" what kind of objects can be put in it! Remember that a variable can contain an instance of the type it was declared as, plus any derived types. So is you have a class hierarchy:

                                class Animal {}
                                class Mammal : Animal {}
                                class Birds : Animal {}
                                class Fish : Animal {}
                                class Reptiles : Animal {}
                                class Amphibian : Animal {}
                                class Fox : Mammal {}

                                Then declaring createurs is legal:

                                Fox fox = new Fox();

                                And

                                Mammal mammal = new Fox();

                                And so is this:

                                Bird eagle = new Eagle();

                                And you can do this:

                                Animal animal = fox;
                                animal = eagle;
                                animal = mammal;

                                But you can't do this:

                                eagle = fox;

                                Or this:

                                eagle = mammal;

                                Or even:

                                fox = eagle;

                                Because they don't make any sense in a real world. Telling C# what type of object a variable can contain means it can catch errors at compile time instead of when your program is running, which makes your code both easier to read and more reliable.

                                Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                                B Offline
                                B Offline
                                Brian_TheLion
                                wrote on last edited by
                                #15

                                Thanks Griff for the examples If you have this code: class Bird : Animal {} Bird eagle = new Eagle(); then saying animal = eagle; is like saying animal = animal as they both should have the same properties. Please correct me if I'm wrong I see what you mean by real world. A bit like saying circle = square Brian

                                OriginalGriffO 1 Reply Last reply
                                0
                                • L Lost User

                                  I agree with OriginalGriff. Telling newbies to use var probably means that they will never use proper types.

                                  B Offline
                                  B Offline
                                  Brian_TheLion
                                  wrote on last edited by
                                  #16

                                  But they are going to read about it in books any way. If it makes coding easier then I'm for it. I can learn the more later. Brian

                                  L 1 Reply Last reply
                                  0
                                  • Richard DeemingR Richard Deeming

                                    For local variables, it's not necessary to repeat the type name: var - C# Reference | Microsoft Docs[^] Implicitly typed local variables - C# Programming Guide | Microsoft Docs[^] The following two lines produce identical IL:

                                    Animal fox = new Animal();
                                    var fox = new Animal();

                                    NB: You can't use var for fields, property types, method parameters, or return types. Why no var on fields? – Fabulous Adventures In Coding[^] There is a suggestion which would allow fields declared as: Animal fox = new();, but it hasn't been implemented yet: csharplang/target-typed-new.md at master · dotnet/csharplang · GitHub[^] NB2: Some people vehemently oppose any use of var beyond anonymous types. And it certainly can be overused - for example, var x = Foo(); would compile, but is not readable. But for a new expression, where the type is right next to the variable declaration, I don't see any problem with using var. NB3: To clarify, based on the responses: using var for new expressions is fine; you should generally avoid it for anything else.

                                    • var x = new SomeType(); is fine.
                                    • var x = SomeMethod(); is bad.

                                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                    B Offline
                                    B Offline
                                    Brian_TheLion
                                    wrote on last edited by
                                    #17

                                    Thanks Richard for the var info. Brian

                                    1 Reply Last reply
                                    0
                                    • OriginalGriffO OriginalGriff

                                      Now I've had some coffee, I'll add some thoughts for you. If you allowed

                                      fox = new animal();

                                      without the type specifier, what problems might it cause? Well, consider this:

                                      public animal fox { get; set; }
                                      public void DoSummat(animal a)
                                      {
                                      fox = a;
                                      ...
                                      }

                                      Is the fox assignment inside DoSummat meant to create a new local instance which is scoped to just the method, or to affect the public property? How could you tell? How could I tell when I tried to fix a problem in 100,000 lines of code next year? Worse, is fox supposed to be an animal, or a mammal, or a Canidae? Does it make a difference? Yes - it does. Because bird is a type of animal but a fox doesn't have a FlapWings method! So if you allow implicit typing, then the compiler has to assume the lowest common type in the hierarchy and that could mean that methods you expect to work just don't exist for that actual instance. And consider this:

                                      public void DoSummat(animal a)
                                      {
                                      fox = a;
                                      ...
                                      fax = b;
                                      ...
                                      }

                                      Isfax a new variable, or did I mistype fox? How would you tell? C# is a strongly typed language: which means that there is no implicit declarations, no automatic type changing (except where data won't be lost such as int to double for example), and heavy duty type checking - which makes your code more robust because it finds problems at compile time, instead of hoping you tested all the possible routes through the code and didn't leave a "bad type" in there.

                                      Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                                      B Offline
                                      B Offline
                                      Brian_TheLion
                                      wrote on last edited by
                                      #18

                                      I do like the way you need to define all variables in C# unlike Python where you could start by attaching a string to a variable then later in the code attach a number to the same variable. Python accepts this without giving any errors It can cause lots of problems in getting a program to work correctly. Speaking of languages I wonder what happened to Visual Basic which was once a popular language. It's no longer in the top 10 popular languages. I suspect C# would be popular with people who have learnt C and C++ as it's simlar in some ways to those languages. I decided to learn C# as I wanted a language to create programs in Windows (that were exe) that had a console and would run fast. Also I prefer compiled code to scripting code. Brian

                                      1 Reply Last reply
                                      0
                                      • Richard DeemingR Richard Deeming

                                        For local variables, it's not necessary to repeat the type name: var - C# Reference | Microsoft Docs[^] Implicitly typed local variables - C# Programming Guide | Microsoft Docs[^] The following two lines produce identical IL:

                                        Animal fox = new Animal();
                                        var fox = new Animal();

                                        NB: You can't use var for fields, property types, method parameters, or return types. Why no var on fields? – Fabulous Adventures In Coding[^] There is a suggestion which would allow fields declared as: Animal fox = new();, but it hasn't been implemented yet: csharplang/target-typed-new.md at master · dotnet/csharplang · GitHub[^] NB2: Some people vehemently oppose any use of var beyond anonymous types. And it certainly can be overused - for example, var x = Foo(); would compile, but is not readable. But for a new expression, where the type is right next to the variable declaration, I don't see any problem with using var. NB3: To clarify, based on the responses: using var for new expressions is fine; you should generally avoid it for anything else.

                                        • var x = new SomeType(); is fine.
                                        • var x = SomeMethod(); is bad.

                                        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                        B Offline
                                        B Offline
                                        Brian_TheLion
                                        wrote on last edited by
                                        #19

                                        Thanks for the links and info Richard. Brian

                                        1 Reply Last reply
                                        0
                                        • L Lost User

                                          Use "var" to help "keep you coding" if you're not sure what type is returned. (Methods; LINQ). THEN, after intelli-sense has resolved the type, you can then "mouse over the var" and convert it to an explicit type ("quick action" refactor). Perfect for a student (and memory-poor me), IMO.

                                          "(I) am amazed to see myself here rather than there ... now rather than then". ― Blaise Pascal

                                          B Offline
                                          B Offline
                                          Brian_TheLion
                                          wrote on last edited by
                                          #20

                                          Yes Gerry I've found intelli-sense very useful. Great tool tool for beginners. Brian

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups