Calling a method from base class to class with same name as the methodCalling the base constructor in C#How do I intercept a method call in C#?How do I use reflection to call a generic method?Best way to repeat a character in C#Call base function then inherited functionCall one constructor from anotherHow to call asynchronous method from synchronous method in C#?How to get all methods for class that inherit from a particular typeWhy not inherit from List<T>?Call matching methods from inherited classes

How can a valley surrounded by mountains be fertile and rainy?

Comment traduire « That screams X »

How to get a character's limb regrown at 3rd level?

Can a nowhere continuous function have a connected graph?

What game is this character in the Pixels movie from?

Different budgets within roommate group

What are good ways to spray paint a QR code on a footpath?

Do home values typically rise and fall at a consistent percent?

Is it okay to fade a human face just to create some space to place important content over it?

I need help with pasta

Do the 26 richest billionaires own as much wealth as the poorest 3.8 billion people?

Converting Geographic Coordinates into Lambert2008 coordinates

If two black hole event horizons overlap (touch) can they ever separate again?

Security Patch SUPEE-11155 - Possible issues?

Bin Packing with Relational Penalization

Adjective for 'made of pus' or 'corrupted by pus' or something of something of pus

Copy group of files (Filename*) to backup (Filename*.bak)

Can you actually break an FPGA by programming it wrong?

How Do I Know When I am in Private Mode?

Golf the smallest circle!

How receiver knows the exact frequency in the channel to "listen to"?

Who are these Discworld wizards from this picture?

Which is better for keeping data: primary partition or logical partition?

How do I tell the reader that my character is autistic in Fantasy?



Calling a method from base class to class with same name as the method


Calling the base constructor in C#How do I intercept a method call in C#?How do I use reflection to call a generic method?Best way to repeat a character in C#Call base function then inherited functionCall one constructor from anotherHow to call asynchronous method from synchronous method in C#?How to get all methods for class that inherit from a particular typeWhy not inherit from List<T>?Call matching methods from inherited classes






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















Summary: B Receives call from A, and automatically starts the start method



Let's say we have class A: A has a function named Start, that start function is initially called from another class (lets refer that class as C) and once it's called, it should call every method from all classes using Start (and using it's base class), with the same method.



And we have B: a class using A as it's base class, it's job is to receive the Start method from A, (initially called by C). Now i could simply do this by calling B's method directly from A, but in this case, B could be named anything, with multiple classes inheriting the same method.



This is useful because i don't want to assign all my variables to one start function. Instead, be able to create a function that allows the same function name to be called.



For example: here's what i was thinking it would look like



class A

public void Start()

// Call B's Start here...



class B : A

public void Start()

// Receive A's call ... and do stuff here




// This time, we also need to access this start method.
// But this class could be named anything
class anotherClass : A

public void Start()

// Receive A's call



class C

static void Main(string[] args)

A a = new A();

// Maybe somehow call all start methods here
a.Start();




But as you can see, Start in class A will be called, but it will never call start in class B.



In better context, I need a way for all Start methods from every class to be called.










share|improve this question






























    0















    Summary: B Receives call from A, and automatically starts the start method



    Let's say we have class A: A has a function named Start, that start function is initially called from another class (lets refer that class as C) and once it's called, it should call every method from all classes using Start (and using it's base class), with the same method.



    And we have B: a class using A as it's base class, it's job is to receive the Start method from A, (initially called by C). Now i could simply do this by calling B's method directly from A, but in this case, B could be named anything, with multiple classes inheriting the same method.



    This is useful because i don't want to assign all my variables to one start function. Instead, be able to create a function that allows the same function name to be called.



    For example: here's what i was thinking it would look like



    class A

    public void Start()

    // Call B's Start here...



    class B : A

    public void Start()

    // Receive A's call ... and do stuff here




    // This time, we also need to access this start method.
    // But this class could be named anything
    class anotherClass : A

    public void Start()

    // Receive A's call



    class C

    static void Main(string[] args)

    A a = new A();

    // Maybe somehow call all start methods here
    a.Start();




    But as you can see, Start in class A will be called, but it will never call start in class B.



    In better context, I need a way for all Start methods from every class to be called.










    share|improve this question


























      0












      0








      0








      Summary: B Receives call from A, and automatically starts the start method



      Let's say we have class A: A has a function named Start, that start function is initially called from another class (lets refer that class as C) and once it's called, it should call every method from all classes using Start (and using it's base class), with the same method.



      And we have B: a class using A as it's base class, it's job is to receive the Start method from A, (initially called by C). Now i could simply do this by calling B's method directly from A, but in this case, B could be named anything, with multiple classes inheriting the same method.



      This is useful because i don't want to assign all my variables to one start function. Instead, be able to create a function that allows the same function name to be called.



      For example: here's what i was thinking it would look like



      class A

      public void Start()

      // Call B's Start here...



      class B : A

      public void Start()

      // Receive A's call ... and do stuff here




      // This time, we also need to access this start method.
      // But this class could be named anything
      class anotherClass : A

      public void Start()

      // Receive A's call



      class C

      static void Main(string[] args)

      A a = new A();

      // Maybe somehow call all start methods here
      a.Start();




      But as you can see, Start in class A will be called, but it will never call start in class B.



      In better context, I need a way for all Start methods from every class to be called.










      share|improve this question
















      Summary: B Receives call from A, and automatically starts the start method



      Let's say we have class A: A has a function named Start, that start function is initially called from another class (lets refer that class as C) and once it's called, it should call every method from all classes using Start (and using it's base class), with the same method.



      And we have B: a class using A as it's base class, it's job is to receive the Start method from A, (initially called by C). Now i could simply do this by calling B's method directly from A, but in this case, B could be named anything, with multiple classes inheriting the same method.



      This is useful because i don't want to assign all my variables to one start function. Instead, be able to create a function that allows the same function name to be called.



      For example: here's what i was thinking it would look like



      class A

      public void Start()

      // Call B's Start here...



      class B : A

      public void Start()

      // Receive A's call ... and do stuff here




      // This time, we also need to access this start method.
      // But this class could be named anything
      class anotherClass : A

      public void Start()

      // Receive A's call



      class C

      static void Main(string[] args)

      A a = new A();

      // Maybe somehow call all start methods here
      a.Start();




      But as you can see, Start in class A will be called, but it will never call start in class B.



      In better context, I need a way for all Start methods from every class to be called.







      c# methods






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 25 at 14:11









      Michał Turczyn

      18.5k13 gold badges22 silver badges41 bronze badges




      18.5k13 gold badges22 silver badges41 bronze badges










      asked Mar 25 at 14:09









      Lost SyndicateLost Syndicate

      85 bronze badges




      85 bronze badges






















          3 Answers
          3






          active

          oldest

          votes


















          0














          You have never created a B or anotherClass object. Therefore their Start method cannot be called.



          Inheritance works the other way round. A derived class can call its base class members, because it knows its ancestor and inherits all its members (fields, properties, methods). The base class (A) on the other side does not know its descendants.



          You must use virtual methods that you can override in derived classes. Example:



          class A

          public virtual void Start()

          Console.WriteLine("Starting A");



          class B : A

          public override void Start()

          base.Start();
          Console.WriteLine("Starting B");




          Now you can create a B object and call its Start method



          var b = new B();
          b.Start();


          This will output:



          Starting A
          Starting B


          Since derived types are assignment compatible to their base types, you can also do something like this



          var list = new List<A> new B(), new A() ;
          foreach (A a in list)
          a.Start();



          Starting A
          Starting B
          Starting A


          where the two first lines are from B.Start() and the last one from A.Start().




          But this works only for classes in the direct lineage. You cannot call methods from siblings. Why? Let's make an example:



          class C : A

          private string s = "hello";

          public override void Start()

          base.Start();
          Console.WriteLine("Starting C: " + s);




          Assuming that you could do something like this in B:



          sibling(C).Start();


          Where should the value "hello" of s come from? Neither A, nor B has such a field and a C object was never created. So your requirement to call every method from all classes cannot be fulfilled. But if a field of A was involved this would work, as B inherits this field.






          share|improve this answer

























          • Thanks, i know now that i have to add each instance of a script, and loop each one until it finds a type with the same base class.

            – Lost Syndicate
            Mar 25 at 14:49











          • You have many options. Every startable class could implement an IStartable interface. The objects could subscribe to a global start event. Or maybe you could do the start thing in the constructor of all the classes.

            – Olivier Jacot-Descombes
            Mar 25 at 15:00


















          1














          Just use reference to base class:



          // or maybe you want to override??
          public new void Start()

          base.Start();



          Use it in every Start class down in class hierarchy






          share|improve this answer






























            0














            You cannot invoke methods on uninitialized classes. So calling A.Start() will not be able to call B.Start() unless an instance of B is initialized. Also, B should notify A of its existance. (Unless you'd use reflection, but I don't suppose that is what you want)



            You may be able to hook B to a with an event with a custom delegate:



            class Program

            static void Main(string[] args)

            var a = new A();
            var b = new B();
            a.StartHandler += b.Start;
            a.Start();

            // Output:
            // A.Start() starting.
            // B.Start() called.
            // A.Start() ending.



            class A

            public delegate void StartMethod();
            public event StartMethod StartHandler;

            public virtual void Start()

            Console.WriteLine("A.Start() starting.");
            if (this.StartHandler != null)

            this.StartHandler();

            Console.WriteLine("A.Start() ending.");



            class B : A

            public override void Start()

            Console.WriteLine("B.Start() called.");




            Another simpler option may be (depending on what you want), to do it the other way, with simple inheritance. If you create an instance of B, you can treat it as if it were an instance of A. So you don't have to know you are actually using a B type under the hood:



            class A

            public virtual void Start() => Console.WriteLine("A.Start()");


            class B : A

            public override void Start()

            Console.WriteLine("B.Start()");
            base.Start();



            // usage:
            A a = new B();
            a.Start();

            // Output:
            // B.Start()
            // A.Start();





            share|improve this answer

























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55339723%2fcalling-a-method-from-base-class-to-class-with-same-name-as-the-method%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              You have never created a B or anotherClass object. Therefore their Start method cannot be called.



              Inheritance works the other way round. A derived class can call its base class members, because it knows its ancestor and inherits all its members (fields, properties, methods). The base class (A) on the other side does not know its descendants.



              You must use virtual methods that you can override in derived classes. Example:



              class A

              public virtual void Start()

              Console.WriteLine("Starting A");



              class B : A

              public override void Start()

              base.Start();
              Console.WriteLine("Starting B");




              Now you can create a B object and call its Start method



              var b = new B();
              b.Start();


              This will output:



              Starting A
              Starting B


              Since derived types are assignment compatible to their base types, you can also do something like this



              var list = new List<A> new B(), new A() ;
              foreach (A a in list)
              a.Start();



              Starting A
              Starting B
              Starting A


              where the two first lines are from B.Start() and the last one from A.Start().




              But this works only for classes in the direct lineage. You cannot call methods from siblings. Why? Let's make an example:



              class C : A

              private string s = "hello";

              public override void Start()

              base.Start();
              Console.WriteLine("Starting C: " + s);




              Assuming that you could do something like this in B:



              sibling(C).Start();


              Where should the value "hello" of s come from? Neither A, nor B has such a field and a C object was never created. So your requirement to call every method from all classes cannot be fulfilled. But if a field of A was involved this would work, as B inherits this field.






              share|improve this answer

























              • Thanks, i know now that i have to add each instance of a script, and loop each one until it finds a type with the same base class.

                – Lost Syndicate
                Mar 25 at 14:49











              • You have many options. Every startable class could implement an IStartable interface. The objects could subscribe to a global start event. Or maybe you could do the start thing in the constructor of all the classes.

                – Olivier Jacot-Descombes
                Mar 25 at 15:00















              0














              You have never created a B or anotherClass object. Therefore their Start method cannot be called.



              Inheritance works the other way round. A derived class can call its base class members, because it knows its ancestor and inherits all its members (fields, properties, methods). The base class (A) on the other side does not know its descendants.



              You must use virtual methods that you can override in derived classes. Example:



              class A

              public virtual void Start()

              Console.WriteLine("Starting A");



              class B : A

              public override void Start()

              base.Start();
              Console.WriteLine("Starting B");




              Now you can create a B object and call its Start method



              var b = new B();
              b.Start();


              This will output:



              Starting A
              Starting B


              Since derived types are assignment compatible to their base types, you can also do something like this



              var list = new List<A> new B(), new A() ;
              foreach (A a in list)
              a.Start();



              Starting A
              Starting B
              Starting A


              where the two first lines are from B.Start() and the last one from A.Start().




              But this works only for classes in the direct lineage. You cannot call methods from siblings. Why? Let's make an example:



              class C : A

              private string s = "hello";

              public override void Start()

              base.Start();
              Console.WriteLine("Starting C: " + s);




              Assuming that you could do something like this in B:



              sibling(C).Start();


              Where should the value "hello" of s come from? Neither A, nor B has such a field and a C object was never created. So your requirement to call every method from all classes cannot be fulfilled. But if a field of A was involved this would work, as B inherits this field.






              share|improve this answer

























              • Thanks, i know now that i have to add each instance of a script, and loop each one until it finds a type with the same base class.

                – Lost Syndicate
                Mar 25 at 14:49











              • You have many options. Every startable class could implement an IStartable interface. The objects could subscribe to a global start event. Or maybe you could do the start thing in the constructor of all the classes.

                – Olivier Jacot-Descombes
                Mar 25 at 15:00













              0












              0








              0







              You have never created a B or anotherClass object. Therefore their Start method cannot be called.



              Inheritance works the other way round. A derived class can call its base class members, because it knows its ancestor and inherits all its members (fields, properties, methods). The base class (A) on the other side does not know its descendants.



              You must use virtual methods that you can override in derived classes. Example:



              class A

              public virtual void Start()

              Console.WriteLine("Starting A");



              class B : A

              public override void Start()

              base.Start();
              Console.WriteLine("Starting B");




              Now you can create a B object and call its Start method



              var b = new B();
              b.Start();


              This will output:



              Starting A
              Starting B


              Since derived types are assignment compatible to their base types, you can also do something like this



              var list = new List<A> new B(), new A() ;
              foreach (A a in list)
              a.Start();



              Starting A
              Starting B
              Starting A


              where the two first lines are from B.Start() and the last one from A.Start().




              But this works only for classes in the direct lineage. You cannot call methods from siblings. Why? Let's make an example:



              class C : A

              private string s = "hello";

              public override void Start()

              base.Start();
              Console.WriteLine("Starting C: " + s);




              Assuming that you could do something like this in B:



              sibling(C).Start();


              Where should the value "hello" of s come from? Neither A, nor B has such a field and a C object was never created. So your requirement to call every method from all classes cannot be fulfilled. But if a field of A was involved this would work, as B inherits this field.






              share|improve this answer















              You have never created a B or anotherClass object. Therefore their Start method cannot be called.



              Inheritance works the other way round. A derived class can call its base class members, because it knows its ancestor and inherits all its members (fields, properties, methods). The base class (A) on the other side does not know its descendants.



              You must use virtual methods that you can override in derived classes. Example:



              class A

              public virtual void Start()

              Console.WriteLine("Starting A");



              class B : A

              public override void Start()

              base.Start();
              Console.WriteLine("Starting B");




              Now you can create a B object and call its Start method



              var b = new B();
              b.Start();


              This will output:



              Starting A
              Starting B


              Since derived types are assignment compatible to their base types, you can also do something like this



              var list = new List<A> new B(), new A() ;
              foreach (A a in list)
              a.Start();



              Starting A
              Starting B
              Starting A


              where the two first lines are from B.Start() and the last one from A.Start().




              But this works only for classes in the direct lineage. You cannot call methods from siblings. Why? Let's make an example:



              class C : A

              private string s = "hello";

              public override void Start()

              base.Start();
              Console.WriteLine("Starting C: " + s);




              Assuming that you could do something like this in B:



              sibling(C).Start();


              Where should the value "hello" of s come from? Neither A, nor B has such a field and a C object was never created. So your requirement to call every method from all classes cannot be fulfilled. But if a field of A was involved this would work, as B inherits this field.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 25 at 14:44

























              answered Mar 25 at 14:22









              Olivier Jacot-DescombesOlivier Jacot-Descombes

              72.1k10 gold badges96 silver badges145 bronze badges




              72.1k10 gold badges96 silver badges145 bronze badges












              • Thanks, i know now that i have to add each instance of a script, and loop each one until it finds a type with the same base class.

                – Lost Syndicate
                Mar 25 at 14:49











              • You have many options. Every startable class could implement an IStartable interface. The objects could subscribe to a global start event. Or maybe you could do the start thing in the constructor of all the classes.

                – Olivier Jacot-Descombes
                Mar 25 at 15:00

















              • Thanks, i know now that i have to add each instance of a script, and loop each one until it finds a type with the same base class.

                – Lost Syndicate
                Mar 25 at 14:49











              • You have many options. Every startable class could implement an IStartable interface. The objects could subscribe to a global start event. Or maybe you could do the start thing in the constructor of all the classes.

                – Olivier Jacot-Descombes
                Mar 25 at 15:00
















              Thanks, i know now that i have to add each instance of a script, and loop each one until it finds a type with the same base class.

              – Lost Syndicate
              Mar 25 at 14:49





              Thanks, i know now that i have to add each instance of a script, and loop each one until it finds a type with the same base class.

              – Lost Syndicate
              Mar 25 at 14:49













              You have many options. Every startable class could implement an IStartable interface. The objects could subscribe to a global start event. Or maybe you could do the start thing in the constructor of all the classes.

              – Olivier Jacot-Descombes
              Mar 25 at 15:00





              You have many options. Every startable class could implement an IStartable interface. The objects could subscribe to a global start event. Or maybe you could do the start thing in the constructor of all the classes.

              – Olivier Jacot-Descombes
              Mar 25 at 15:00













              1














              Just use reference to base class:



              // or maybe you want to override??
              public new void Start()

              base.Start();



              Use it in every Start class down in class hierarchy






              share|improve this answer



























                1














                Just use reference to base class:



                // or maybe you want to override??
                public new void Start()

                base.Start();



                Use it in every Start class down in class hierarchy






                share|improve this answer

























                  1












                  1








                  1







                  Just use reference to base class:



                  // or maybe you want to override??
                  public new void Start()

                  base.Start();



                  Use it in every Start class down in class hierarchy






                  share|improve this answer













                  Just use reference to base class:



                  // or maybe you want to override??
                  public new void Start()

                  base.Start();



                  Use it in every Start class down in class hierarchy







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 25 at 14:11









                  Michał TurczynMichał Turczyn

                  18.5k13 gold badges22 silver badges41 bronze badges




                  18.5k13 gold badges22 silver badges41 bronze badges





















                      0














                      You cannot invoke methods on uninitialized classes. So calling A.Start() will not be able to call B.Start() unless an instance of B is initialized. Also, B should notify A of its existance. (Unless you'd use reflection, but I don't suppose that is what you want)



                      You may be able to hook B to a with an event with a custom delegate:



                      class Program

                      static void Main(string[] args)

                      var a = new A();
                      var b = new B();
                      a.StartHandler += b.Start;
                      a.Start();

                      // Output:
                      // A.Start() starting.
                      // B.Start() called.
                      // A.Start() ending.



                      class A

                      public delegate void StartMethod();
                      public event StartMethod StartHandler;

                      public virtual void Start()

                      Console.WriteLine("A.Start() starting.");
                      if (this.StartHandler != null)

                      this.StartHandler();

                      Console.WriteLine("A.Start() ending.");



                      class B : A

                      public override void Start()

                      Console.WriteLine("B.Start() called.");




                      Another simpler option may be (depending on what you want), to do it the other way, with simple inheritance. If you create an instance of B, you can treat it as if it were an instance of A. So you don't have to know you are actually using a B type under the hood:



                      class A

                      public virtual void Start() => Console.WriteLine("A.Start()");


                      class B : A

                      public override void Start()

                      Console.WriteLine("B.Start()");
                      base.Start();



                      // usage:
                      A a = new B();
                      a.Start();

                      // Output:
                      // B.Start()
                      // A.Start();





                      share|improve this answer



























                        0














                        You cannot invoke methods on uninitialized classes. So calling A.Start() will not be able to call B.Start() unless an instance of B is initialized. Also, B should notify A of its existance. (Unless you'd use reflection, but I don't suppose that is what you want)



                        You may be able to hook B to a with an event with a custom delegate:



                        class Program

                        static void Main(string[] args)

                        var a = new A();
                        var b = new B();
                        a.StartHandler += b.Start;
                        a.Start();

                        // Output:
                        // A.Start() starting.
                        // B.Start() called.
                        // A.Start() ending.



                        class A

                        public delegate void StartMethod();
                        public event StartMethod StartHandler;

                        public virtual void Start()

                        Console.WriteLine("A.Start() starting.");
                        if (this.StartHandler != null)

                        this.StartHandler();

                        Console.WriteLine("A.Start() ending.");



                        class B : A

                        public override void Start()

                        Console.WriteLine("B.Start() called.");




                        Another simpler option may be (depending on what you want), to do it the other way, with simple inheritance. If you create an instance of B, you can treat it as if it were an instance of A. So you don't have to know you are actually using a B type under the hood:



                        class A

                        public virtual void Start() => Console.WriteLine("A.Start()");


                        class B : A

                        public override void Start()

                        Console.WriteLine("B.Start()");
                        base.Start();



                        // usage:
                        A a = new B();
                        a.Start();

                        // Output:
                        // B.Start()
                        // A.Start();





                        share|improve this answer

























                          0












                          0








                          0







                          You cannot invoke methods on uninitialized classes. So calling A.Start() will not be able to call B.Start() unless an instance of B is initialized. Also, B should notify A of its existance. (Unless you'd use reflection, but I don't suppose that is what you want)



                          You may be able to hook B to a with an event with a custom delegate:



                          class Program

                          static void Main(string[] args)

                          var a = new A();
                          var b = new B();
                          a.StartHandler += b.Start;
                          a.Start();

                          // Output:
                          // A.Start() starting.
                          // B.Start() called.
                          // A.Start() ending.



                          class A

                          public delegate void StartMethod();
                          public event StartMethod StartHandler;

                          public virtual void Start()

                          Console.WriteLine("A.Start() starting.");
                          if (this.StartHandler != null)

                          this.StartHandler();

                          Console.WriteLine("A.Start() ending.");



                          class B : A

                          public override void Start()

                          Console.WriteLine("B.Start() called.");




                          Another simpler option may be (depending on what you want), to do it the other way, with simple inheritance. If you create an instance of B, you can treat it as if it were an instance of A. So you don't have to know you are actually using a B type under the hood:



                          class A

                          public virtual void Start() => Console.WriteLine("A.Start()");


                          class B : A

                          public override void Start()

                          Console.WriteLine("B.Start()");
                          base.Start();



                          // usage:
                          A a = new B();
                          a.Start();

                          // Output:
                          // B.Start()
                          // A.Start();





                          share|improve this answer













                          You cannot invoke methods on uninitialized classes. So calling A.Start() will not be able to call B.Start() unless an instance of B is initialized. Also, B should notify A of its existance. (Unless you'd use reflection, but I don't suppose that is what you want)



                          You may be able to hook B to a with an event with a custom delegate:



                          class Program

                          static void Main(string[] args)

                          var a = new A();
                          var b = new B();
                          a.StartHandler += b.Start;
                          a.Start();

                          // Output:
                          // A.Start() starting.
                          // B.Start() called.
                          // A.Start() ending.



                          class A

                          public delegate void StartMethod();
                          public event StartMethod StartHandler;

                          public virtual void Start()

                          Console.WriteLine("A.Start() starting.");
                          if (this.StartHandler != null)

                          this.StartHandler();

                          Console.WriteLine("A.Start() ending.");



                          class B : A

                          public override void Start()

                          Console.WriteLine("B.Start() called.");




                          Another simpler option may be (depending on what you want), to do it the other way, with simple inheritance. If you create an instance of B, you can treat it as if it were an instance of A. So you don't have to know you are actually using a B type under the hood:



                          class A

                          public virtual void Start() => Console.WriteLine("A.Start()");


                          class B : A

                          public override void Start()

                          Console.WriteLine("B.Start()");
                          base.Start();



                          // usage:
                          A a = new B();
                          a.Start();

                          // Output:
                          // B.Start()
                          // A.Start();






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 25 at 14:32









                          Jesse de WitJesse de Wit

                          8697 silver badges23 bronze badges




                          8697 silver badges23 bronze badges



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55339723%2fcalling-a-method-from-base-class-to-class-with-same-name-as-the-method%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                              용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                              155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해