How to access the first base class in C#?











up vote
2
down vote

favorite












I'm having a base class defined in my app



Something like,



using System;

public class BaseClass
{
public virtual void Method2() {Console.WriteLine("base2");}
public virtual void Method1() {Console.WriteLine("base1");}
}
public class Derived1 : BaseClass
{
public override void Method2() {Console.WriteLine("derived1-2");}
public override void Method1() {Console.WriteLine("derived1-1");}
}
public class Derived2 : Derived1
{
public override void Method1() {Console.WriteLine("derived2-2");}


}
public class Program
{
public static void Main()
{
var obj = new Derived2();
((BaseClass)obj).Method2();
Console.WriteLine("Hello World");
}
}


Say I need to access the Method2() of my very first BaseClass. Even after typecasting it to ((BaseClass)obj).Method2(), I'm still getting derived1-2 while I'm expecting base2'.



How do I do that ?










share|improve this question


















  • 3




    BaseClass was (apparently) designed so that calls to Method2 resolve to the most specific type which overrides that method. If you don't want that to happen, you need to redesign your base classes or hierarchy. It could be done in IL (call vs callvirt) but not expressible in C#
    – Damien_The_Unbeliever
    Nov 19 at 14:08












  • stackoverflow.com/questions/8329470/…
    – Jonesopolis
    Nov 19 at 14:08






  • 7




    You don't. That's what virtual is all about. If you want the method to remain accessible as-is to derived classes, provide a (protected) non-virtual implementation that the virtual method calls.
    – Jeroen Mostert
    Nov 19 at 14:08








  • 1




    If you want a method to be determined by the variable's type and not the actual object's type then don't use virtual and then use new instead of override.
    – juharr
    Nov 19 at 14:15








  • 2




    As a side-note to this conversation, having a class that overrides inherited functionality is risky. You should call the inherited class's method, then your extra code in your override. For example, perhaps the base class has some validation code to prevent bad calls, you'd be skipping that check if you completely override the method. Maybe I've been reading too much Bob Martin :( p.s. Maybe your base class should have had "Open for Extension" in mind when it was being created ^^
    – Dan Rayson
    Nov 19 at 14:20

















up vote
2
down vote

favorite












I'm having a base class defined in my app



Something like,



using System;

public class BaseClass
{
public virtual void Method2() {Console.WriteLine("base2");}
public virtual void Method1() {Console.WriteLine("base1");}
}
public class Derived1 : BaseClass
{
public override void Method2() {Console.WriteLine("derived1-2");}
public override void Method1() {Console.WriteLine("derived1-1");}
}
public class Derived2 : Derived1
{
public override void Method1() {Console.WriteLine("derived2-2");}


}
public class Program
{
public static void Main()
{
var obj = new Derived2();
((BaseClass)obj).Method2();
Console.WriteLine("Hello World");
}
}


Say I need to access the Method2() of my very first BaseClass. Even after typecasting it to ((BaseClass)obj).Method2(), I'm still getting derived1-2 while I'm expecting base2'.



How do I do that ?










share|improve this question


















  • 3




    BaseClass was (apparently) designed so that calls to Method2 resolve to the most specific type which overrides that method. If you don't want that to happen, you need to redesign your base classes or hierarchy. It could be done in IL (call vs callvirt) but not expressible in C#
    – Damien_The_Unbeliever
    Nov 19 at 14:08












  • stackoverflow.com/questions/8329470/…
    – Jonesopolis
    Nov 19 at 14:08






  • 7




    You don't. That's what virtual is all about. If you want the method to remain accessible as-is to derived classes, provide a (protected) non-virtual implementation that the virtual method calls.
    – Jeroen Mostert
    Nov 19 at 14:08








  • 1




    If you want a method to be determined by the variable's type and not the actual object's type then don't use virtual and then use new instead of override.
    – juharr
    Nov 19 at 14:15








  • 2




    As a side-note to this conversation, having a class that overrides inherited functionality is risky. You should call the inherited class's method, then your extra code in your override. For example, perhaps the base class has some validation code to prevent bad calls, you'd be skipping that check if you completely override the method. Maybe I've been reading too much Bob Martin :( p.s. Maybe your base class should have had "Open for Extension" in mind when it was being created ^^
    – Dan Rayson
    Nov 19 at 14:20















up vote
2
down vote

favorite









up vote
2
down vote

favorite











I'm having a base class defined in my app



Something like,



using System;

public class BaseClass
{
public virtual void Method2() {Console.WriteLine("base2");}
public virtual void Method1() {Console.WriteLine("base1");}
}
public class Derived1 : BaseClass
{
public override void Method2() {Console.WriteLine("derived1-2");}
public override void Method1() {Console.WriteLine("derived1-1");}
}
public class Derived2 : Derived1
{
public override void Method1() {Console.WriteLine("derived2-2");}


}
public class Program
{
public static void Main()
{
var obj = new Derived2();
((BaseClass)obj).Method2();
Console.WriteLine("Hello World");
}
}


Say I need to access the Method2() of my very first BaseClass. Even after typecasting it to ((BaseClass)obj).Method2(), I'm still getting derived1-2 while I'm expecting base2'.



How do I do that ?










share|improve this question













I'm having a base class defined in my app



Something like,



using System;

public class BaseClass
{
public virtual void Method2() {Console.WriteLine("base2");}
public virtual void Method1() {Console.WriteLine("base1");}
}
public class Derived1 : BaseClass
{
public override void Method2() {Console.WriteLine("derived1-2");}
public override void Method1() {Console.WriteLine("derived1-1");}
}
public class Derived2 : Derived1
{
public override void Method1() {Console.WriteLine("derived2-2");}


}
public class Program
{
public static void Main()
{
var obj = new Derived2();
((BaseClass)obj).Method2();
Console.WriteLine("Hello World");
}
}


Say I need to access the Method2() of my very first BaseClass. Even after typecasting it to ((BaseClass)obj).Method2(), I'm still getting derived1-2 while I'm expecting base2'.



How do I do that ?







c# .net






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 19 at 14:05









now he who must not be named.

4,8061554100




4,8061554100








  • 3




    BaseClass was (apparently) designed so that calls to Method2 resolve to the most specific type which overrides that method. If you don't want that to happen, you need to redesign your base classes or hierarchy. It could be done in IL (call vs callvirt) but not expressible in C#
    – Damien_The_Unbeliever
    Nov 19 at 14:08












  • stackoverflow.com/questions/8329470/…
    – Jonesopolis
    Nov 19 at 14:08






  • 7




    You don't. That's what virtual is all about. If you want the method to remain accessible as-is to derived classes, provide a (protected) non-virtual implementation that the virtual method calls.
    – Jeroen Mostert
    Nov 19 at 14:08








  • 1




    If you want a method to be determined by the variable's type and not the actual object's type then don't use virtual and then use new instead of override.
    – juharr
    Nov 19 at 14:15








  • 2




    As a side-note to this conversation, having a class that overrides inherited functionality is risky. You should call the inherited class's method, then your extra code in your override. For example, perhaps the base class has some validation code to prevent bad calls, you'd be skipping that check if you completely override the method. Maybe I've been reading too much Bob Martin :( p.s. Maybe your base class should have had "Open for Extension" in mind when it was being created ^^
    – Dan Rayson
    Nov 19 at 14:20
















  • 3




    BaseClass was (apparently) designed so that calls to Method2 resolve to the most specific type which overrides that method. If you don't want that to happen, you need to redesign your base classes or hierarchy. It could be done in IL (call vs callvirt) but not expressible in C#
    – Damien_The_Unbeliever
    Nov 19 at 14:08












  • stackoverflow.com/questions/8329470/…
    – Jonesopolis
    Nov 19 at 14:08






  • 7




    You don't. That's what virtual is all about. If you want the method to remain accessible as-is to derived classes, provide a (protected) non-virtual implementation that the virtual method calls.
    – Jeroen Mostert
    Nov 19 at 14:08








  • 1




    If you want a method to be determined by the variable's type and not the actual object's type then don't use virtual and then use new instead of override.
    – juharr
    Nov 19 at 14:15








  • 2




    As a side-note to this conversation, having a class that overrides inherited functionality is risky. You should call the inherited class's method, then your extra code in your override. For example, perhaps the base class has some validation code to prevent bad calls, you'd be skipping that check if you completely override the method. Maybe I've been reading too much Bob Martin :( p.s. Maybe your base class should have had "Open for Extension" in mind when it was being created ^^
    – Dan Rayson
    Nov 19 at 14:20










3




3




BaseClass was (apparently) designed so that calls to Method2 resolve to the most specific type which overrides that method. If you don't want that to happen, you need to redesign your base classes or hierarchy. It could be done in IL (call vs callvirt) but not expressible in C#
– Damien_The_Unbeliever
Nov 19 at 14:08






BaseClass was (apparently) designed so that calls to Method2 resolve to the most specific type which overrides that method. If you don't want that to happen, you need to redesign your base classes or hierarchy. It could be done in IL (call vs callvirt) but not expressible in C#
– Damien_The_Unbeliever
Nov 19 at 14:08














stackoverflow.com/questions/8329470/…
– Jonesopolis
Nov 19 at 14:08




stackoverflow.com/questions/8329470/…
– Jonesopolis
Nov 19 at 14:08




7




7




You don't. That's what virtual is all about. If you want the method to remain accessible as-is to derived classes, provide a (protected) non-virtual implementation that the virtual method calls.
– Jeroen Mostert
Nov 19 at 14:08






You don't. That's what virtual is all about. If you want the method to remain accessible as-is to derived classes, provide a (protected) non-virtual implementation that the virtual method calls.
– Jeroen Mostert
Nov 19 at 14:08






1




1




If you want a method to be determined by the variable's type and not the actual object's type then don't use virtual and then use new instead of override.
– juharr
Nov 19 at 14:15






If you want a method to be determined by the variable's type and not the actual object's type then don't use virtual and then use new instead of override.
– juharr
Nov 19 at 14:15






2




2




As a side-note to this conversation, having a class that overrides inherited functionality is risky. You should call the inherited class's method, then your extra code in your override. For example, perhaps the base class has some validation code to prevent bad calls, you'd be skipping that check if you completely override the method. Maybe I've been reading too much Bob Martin :( p.s. Maybe your base class should have had "Open for Extension" in mind when it was being created ^^
– Dan Rayson
Nov 19 at 14:20






As a side-note to this conversation, having a class that overrides inherited functionality is risky. You should call the inherited class's method, then your extra code in your override. For example, perhaps the base class has some validation code to prevent bad calls, you'd be skipping that check if you completely override the method. Maybe I've been reading too much Bob Martin :( p.s. Maybe your base class should have had "Open for Extension" in mind when it was being created ^^
– Dan Rayson
Nov 19 at 14:20














1 Answer
1






active

oldest

votes

















up vote
1
down vote













I completely agree with the comments: it sounds like the behaviour that you require would need you to re-think your classes - possibly inheritance is not the best solution in this case. It depends what you're trying to do; you could obviously just do this:



var obj = new BaseClass();
((BaseClass)obj).Method2();
Console.WriteLine("Hello World");


My guess would be that what you actually want here is some form of injection; for example:



public class BaseClass
{
private readonly IFunctionality1 functionality1;

public virtual void Method2() { Console.WriteLine("base2"); }
public virtual void Method1() { this.functionality1.Method1(); }

public BaseClass(IFunctionality1 functionality1)
{
this.functionality1 = functionality1;
}
}
public class Derived1 : BaseClass
{
public Derived1(IFunctionality1 functionality1) : base (functionality1)
{

}

}


In this case, you might find that inheritance isn't even required anymore.






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',
    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%2f53376371%2fhow-to-access-the-first-base-class-in-c%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote













    I completely agree with the comments: it sounds like the behaviour that you require would need you to re-think your classes - possibly inheritance is not the best solution in this case. It depends what you're trying to do; you could obviously just do this:



    var obj = new BaseClass();
    ((BaseClass)obj).Method2();
    Console.WriteLine("Hello World");


    My guess would be that what you actually want here is some form of injection; for example:



    public class BaseClass
    {
    private readonly IFunctionality1 functionality1;

    public virtual void Method2() { Console.WriteLine("base2"); }
    public virtual void Method1() { this.functionality1.Method1(); }

    public BaseClass(IFunctionality1 functionality1)
    {
    this.functionality1 = functionality1;
    }
    }
    public class Derived1 : BaseClass
    {
    public Derived1(IFunctionality1 functionality1) : base (functionality1)
    {

    }

    }


    In this case, you might find that inheritance isn't even required anymore.






    share|improve this answer



























      up vote
      1
      down vote













      I completely agree with the comments: it sounds like the behaviour that you require would need you to re-think your classes - possibly inheritance is not the best solution in this case. It depends what you're trying to do; you could obviously just do this:



      var obj = new BaseClass();
      ((BaseClass)obj).Method2();
      Console.WriteLine("Hello World");


      My guess would be that what you actually want here is some form of injection; for example:



      public class BaseClass
      {
      private readonly IFunctionality1 functionality1;

      public virtual void Method2() { Console.WriteLine("base2"); }
      public virtual void Method1() { this.functionality1.Method1(); }

      public BaseClass(IFunctionality1 functionality1)
      {
      this.functionality1 = functionality1;
      }
      }
      public class Derived1 : BaseClass
      {
      public Derived1(IFunctionality1 functionality1) : base (functionality1)
      {

      }

      }


      In this case, you might find that inheritance isn't even required anymore.






      share|improve this answer

























        up vote
        1
        down vote










        up vote
        1
        down vote









        I completely agree with the comments: it sounds like the behaviour that you require would need you to re-think your classes - possibly inheritance is not the best solution in this case. It depends what you're trying to do; you could obviously just do this:



        var obj = new BaseClass();
        ((BaseClass)obj).Method2();
        Console.WriteLine("Hello World");


        My guess would be that what you actually want here is some form of injection; for example:



        public class BaseClass
        {
        private readonly IFunctionality1 functionality1;

        public virtual void Method2() { Console.WriteLine("base2"); }
        public virtual void Method1() { this.functionality1.Method1(); }

        public BaseClass(IFunctionality1 functionality1)
        {
        this.functionality1 = functionality1;
        }
        }
        public class Derived1 : BaseClass
        {
        public Derived1(IFunctionality1 functionality1) : base (functionality1)
        {

        }

        }


        In this case, you might find that inheritance isn't even required anymore.






        share|improve this answer














        I completely agree with the comments: it sounds like the behaviour that you require would need you to re-think your classes - possibly inheritance is not the best solution in this case. It depends what you're trying to do; you could obviously just do this:



        var obj = new BaseClass();
        ((BaseClass)obj).Method2();
        Console.WriteLine("Hello World");


        My guess would be that what you actually want here is some form of injection; for example:



        public class BaseClass
        {
        private readonly IFunctionality1 functionality1;

        public virtual void Method2() { Console.WriteLine("base2"); }
        public virtual void Method1() { this.functionality1.Method1(); }

        public BaseClass(IFunctionality1 functionality1)
        {
        this.functionality1 = functionality1;
        }
        }
        public class Derived1 : BaseClass
        {
        public Derived1(IFunctionality1 functionality1) : base (functionality1)
        {

        }

        }


        In this case, you might find that inheritance isn't even required anymore.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 19 at 16:36









        Fildor

        7,07832146




        7,07832146










        answered Nov 19 at 14:26









        pm_2

        6,50430117213




        6,50430117213






























            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.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • 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%2f53376371%2fhow-to-access-the-first-base-class-in-c%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

            If I really need a card on my start hand, how many mulligans make sense? [duplicate]

            Alcedinidae

            Can an atomic nucleus contain both particles and antiparticles? [duplicate]