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 Brian_TheLion

    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 Offline
    OriginalGriffO Offline
    OriginalGriff
    wrote on last edited by
    #21

    public class Animal
    {
    public void Breathe() {}
    }
    public class Bird : Animal
    {
    public void FlapWings() {}
    }
    public class Eagle : Bird
    {
    public void DiveVeryQuicklyOntoOtherBird(Bird target) {}
    }
    ...
    Bird eagle = new Eagle();
    Animal animal = eagle;

    That's completely legal because Eagle is derived from Bird, which derives from Animal: an Eagle is a Bird, which is an Animal. But ... it's legal to say these:

    eagle.FlapWings();
    eagle.Breathe();

    Because eagle is a variable containing a Bird instance (or an instance of a class derived from Bird), so it has all the properties and methods of a Bird as well as those of an Animal But ... you can't do this:

    eagle.DiveVeryQuicklyOntoOtherBird(myPigeon);

    Because not all the types that can be held in a Bird variable are Eagles; they could be any Bird - so they don't all support the DiveVeryQuicklyOntoOtherBird method - despite the variable currently containing an instance of an Eagle the system doesn't "know" that it always will; at a later point you could replace it with

    eagle = new Sparrow();

    which can't dive really quickly like an apex predator! To use the method you'd need to cast the instance:

            ((Eagle)eagle).DiveVeryQuicklyOntoOtherBird(new Sparrow());
    

    Or use an Eagle variable. If you try to cast a Sparrow to an Eagle, you will get an error at run time, because that's the only time when it can check if the conversion is possible.

    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

      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 Offline
      L Offline
      Lost User
      wrote on last edited by
      #22

      Brian_TheLion wrote:

      I can learn the more later.

      Learning things in the wrong order is a sure way to failure.

      B 1 Reply Last reply
      0
      • L Lost User

        Brian_TheLion wrote:

        I can learn the more later.

        Learning things in the wrong order is a sure way to failure.

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

        Yes that is true but it's good to know that 'var' exists. I find that I'm best at learning programming by studying medium sized programs. I like to step thru a program to see how it works. I also try to write a simple C# program from what I have learnt. I suspect the biggest thing that turns beginners away from learning C# is when their program is fulled with errors and they have no idea on how to fix the problem or where they went wrong as they have tried to build a complex program before fully learning C#. Jumping in the deep end as they say. Things like l1.addExit(new Exit(Exit.Directions.North, l2)); takes a bit of getting use to but I'm keen to learn and are starting to understand it more. Brian

        B 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
          BillWoodruff
          wrote on last edited by
          #24

          Some good caffeine in there ! :omg:

          «Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot

          OriginalGriffO 1 Reply Last reply
          0
          • B Brian_TheLion

            Yes that is true but it's good to know that 'var' exists. I find that I'm best at learning programming by studying medium sized programs. I like to step thru a program to see how it works. I also try to write a simple C# program from what I have learnt. I suspect the biggest thing that turns beginners away from learning C# is when their program is fulled with errors and they have no idea on how to fix the problem or where they went wrong as they have tried to build a complex program before fully learning C#. Jumping in the deep end as they say. Things like l1.addExit(new Exit(Exit.Directions.North, l2)); takes a bit of getting use to but I'm keen to learn and are starting to understand it more. Brian

            B Offline
            B Offline
            BillWoodruff
            wrote on last edited by
            #25

            Brian_TheLion wrote:

            I suspect the biggest thing that turns beginners away from learning C# is when their program is fulled with errors

            When I see a student whose code is full of errors (beyond typos), I see a student who is not being guided properly, or, a student who is "flailing" because they have not grounded themselves in language basics, or don't know how to study in a disciplined way. Once you make some progress in getting over the initial learning curve with C#, I predict you will look back on VB and Python as the messes they are :)

            «Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot

            B 1 Reply Last reply
            0
            • OriginalGriffO OriginalGriff

              public class Animal
              {
              public void Breathe() {}
              }
              public class Bird : Animal
              {
              public void FlapWings() {}
              }
              public class Eagle : Bird
              {
              public void DiveVeryQuicklyOntoOtherBird(Bird target) {}
              }
              ...
              Bird eagle = new Eagle();
              Animal animal = eagle;

              That's completely legal because Eagle is derived from Bird, which derives from Animal: an Eagle is a Bird, which is an Animal. But ... it's legal to say these:

              eagle.FlapWings();
              eagle.Breathe();

              Because eagle is a variable containing a Bird instance (or an instance of a class derived from Bird), so it has all the properties and methods of a Bird as well as those of an Animal But ... you can't do this:

              eagle.DiveVeryQuicklyOntoOtherBird(myPigeon);

              Because not all the types that can be held in a Bird variable are Eagles; they could be any Bird - so they don't all support the DiveVeryQuicklyOntoOtherBird method - despite the variable currently containing an instance of an Eagle the system doesn't "know" that it always will; at a later point you could replace it with

              eagle = new Sparrow();

              which can't dive really quickly like an apex predator! To use the method you'd need to cast the instance:

                      ((Eagle)eagle).DiveVeryQuicklyOntoOtherBird(new Sparrow());
              

              Or use an Eagle variable. If you try to cast a Sparrow to an Eagle, you will get an error at run time, because that's the only time when it can check if the conversion is possible.

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

              Thanks Griff. I liked examples like these you've given me. You wrote:: eagle = new Sparrow() I thought you may have to use: Bird eagle = new Sparrow() . Is it because you have already defined the eagle as a bird (Bird eagle = new Eagle();) that you don't need to do this? Brian

              OriginalGriffO 1 Reply Last reply
              0
              • B BillWoodruff

                Brian_TheLion wrote:

                I suspect the biggest thing that turns beginners away from learning C# is when their program is fulled with errors

                When I see a student whose code is full of errors (beyond typos), I see a student who is not being guided properly, or, a student who is "flailing" because they have not grounded themselves in language basics, or don't know how to study in a disciplined way. Once you make some progress in getting over the initial learning curve with C#, I predict you will look back on VB and Python as the messes they are :)

                «Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot

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

                Hi Bill. I hope your right. You do get some lift of confidence when the program runs without errors. With me it's a case of getting out of the habit of script coding like I did with Basic and QuickBasic. Brian

                1 Reply Last reply
                0
                • B BillWoodruff

                  Some good caffeine in there ! :omg:

                  «Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot

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

                  Heavy duty wake up juice! ;)

                  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

                  1 Reply Last reply
                  0
                  • B Brian_TheLion

                    Thanks Griff. I liked examples like these you've given me. You wrote:: eagle = new Sparrow() I thought you may have to use: Bird eagle = new Sparrow() . Is it because you have already defined the eagle as a bird (Bird eagle = new Eagle();) that you don't need to do this? Brian

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

                    If you do this:

                    private void DoSummat()
                    {
                    Bird eagle = new Eagle();
                    ...
                    eagle = new Sparrow();
                    ...
                    }

                    You are just reusing the existing variable, like you do without worrying about classes:

                    int i = 1;
                    while (true)
                    {
                    Console.WriteLine(i);
                    i = i + 1;
                    }

                    If you tried to create a new variable with the same name in the same scope:

                    private void DoSummat()
                    {
                    Bird eagle = new Eagle();
                    ...
                    Bird eagle = new Sparrow();
                    ...
                    }

                    You would get an error as it already exists - just the same as you can't do this:

                    for (int i = 0; i < 10; i++)
                    {
                    Console.Write($"{i} :");
                    for (int i = 100; i < 110; i++)
                    {
                    Console.Write(i);
                    }
                    Console.WriteLine();
                    }

                    You can't have two loop guards with the same name! Or even this:

                    private void DoSummat(int x)
                    {
                    int x = 666;
                    ...
                    }

                    Because the parameter and variable are the same name.

                    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

                    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!

                      J Offline
                      J Offline
                      jschell
                      wrote on last edited by
                      #30

                      OriginalGriff wrote:

                      without the type specifier, what problems might it cause?

                      Hmmm...I can see the compiler struggling a bit with the following.... var fox = new;

                      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