How can I prevent a base constructor from being called by an inheritor in C#?

7,596

Solution 1

If you do not explicitly call any constructor in the base class, the parameterless constructor will be called implicitly. There's no way around it, you cannot instantiate a class without a constructor being called.

Solution 2

There is a way to create an object without calling any instance constructors.

Before you proceed, be very sure you want to do it this way. 99% of the time this is the wrong solution.

This is how you do it:

FormatterServices.GetUninitializedObject(typeof(MyClass));

Call it in place of the object's constructor. It will create and return you an instance without calling any constructors or field initializers.

When you deserialize an object in WCF, it uses this method to create the object. When this happens, constructors and even field initializers are not run.

Solution 3

At least 1 ctor has to be called. The only way around it I see is containment. Have the class inside or referencing the other class.

Solution 4

If what you want is to not call either of the two base class constructors, this cannot be done.

C# class constructors must call base class constructors. If you don't call one explicitly, base( ) is implied. In your example, if you do not specify which base class constructor to call, it is the same as:

public BaseClassProxy : BaseClass
{
    public BaseClassProxy() : base() { }
}

If you prefer to use the other base class constructor, you can use:

public BaseClassProxy : BaseClass
{
    public BaseClassProxy() : base(someIntValue) { }
}

Either way, one of the two will be called, explicitly or implicitly.

Solution 5

I don't believe you can get around calling the constructor. But you could do something like this:

public class BaseClass : SomeOtherBase 
{
   public BaseClass() {}

   protected virtual void Setup()
   {
   }
}

public BaseClassProxy : BaseClass
{
   bool _fakeOut;
   protected BaseClassProxy(bool fakeOut)
   {
        _fakeOut = fakeOut;
        Setup();
   }

   public override void Setup()
   {
       if(_fakeOut)
       {
            base.Setup();
       }
       //Your other constructor code
   }
} 
Share:
7,596
user2266675
Author by

user2266675

Updated on January 17, 2021

Comments

  • user2266675
    user2266675 over 3 years

    I'm running into an issue of conflicting JQuery between a sliding navigation and a slider. Any help would be appreciated! In Chrome Console, I'm getting:

    Uncaught ReferenceError: $ is not defined smooth-scroll.js:2
    Uncaught ReferenceError: jQuery is not defined jquery.sticky.js:112
    Uncaught ReferenceError: jQuery is not defined jquery.fancybox-1.3.4.pack.js:46
    Uncaught ReferenceError: jQuery is not defined
    Uncaught ReferenceError: jQuery is not defined jquery.mousewheel-3.0.4.pack.js:14
    Uncaught ReferenceError: $ is not defined index.html:46
    Uncaught ReferenceError: $ is not defined index.html:52
    

    Here is my header:

    <head>
      <meta charset="utf-8">
        <title>DCC Marketing - Decatur Illinois Public Relations, Advertising, Strategic Planning, & Web Development</title>
        <meta name="description" content="" />
        <meta name="keywords" content="" />
        <meta name="robots" content="" />
    
        <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Oxygen">
        <link href="css/reset.css" rel="stylesheet" type="text/css" />
        <link href="css/960.css" rel="stylesheet" type="text/css" />
        <link href="css/styles.css" rel="stylesheet" type="text/css" />
        <link href="fancybox/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" />
    
    
        <link rel="stylesheet" href="css/example.css">
        <style>
            body {-webkit-font-smoothing: antialiased;font: normal 15px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;}
            #slides {display: none;margin-top:36px;}
            .slidesjs-container {width:1000px;height:252px;margin-bottom:-21px;}
            #slides .slidesjs-navigation {margin-top:-17px;visibility: hidden;}
            #slides .slidesjs-previous {margin-right: 5px;float: left;visibility: hidden;}
            #slides .slidesjs-next {margin-right: 5px;float: left;visibility: hidden;}
            .slidesjs-pagination {margin: 0px 6px 0;float: right;list-style: none;position:relative;z-index:1000;}
            .slidesjs-pagination li {float: left;margin: 0 1px;}
            .slidesjs-pagination li a {visibility:hidden;display: block;width: 14px;height: 0;padding-top: 14px;background-image: url(images/pagination.png);background-position: 0 0;float: left;overflow: hidden;}
            .slidesjs-pagination li a.active,
            .slidesjs-pagination li a:hover.active {background-position: 0 -14px}
            .slidesjs-pagination li a:hover {background-position: 0 -28px}
            #slides a:link,
            #slides a:visited {color: #333}
            #slides a:hover,
            #slides a:active {color: #9e2020}
            .navbar {overflow: hidden}
        </style>
    
        <script type="text/javascript" src="js/smooth-scroll.js"></script>
        <script type="text/javascript" src="js/jquery.sticky.js"></script>
        <script type="text/javascript" src="fancybox/jquery.fancybox-1.3.4.pack.js"></script>
        <script type="text/javascript" src="js/jquery.easing-1.3.pack.js"></script>
        <script type="text/javascript" src="fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
        <script type="text/javascript" src="cform.js"></script>
    
    <script type="text/javascript"> // sticky nav bar 
      $(document).ready(function(){
        $("nav").sticky({topSpacing:0});
      });
    </script>
    
    <script type="text/javascript"> // fancybox
    $(document).ready(function() {
    
        $("a.single_image").fancybox();
    
        $("a#inline").fancybox({
            'hideOnContentClick': true
        });
    
        $("a.group").fancybox({
            'transitionIn'  :   'elastic',
            'transitionOut' :   'elastic',
            'speedIn'       :   600, 
            'speedOut'      :   900, 
            'overlayShow'   :   false
        });
    
    });
    </script>
    </head>
    

    And here is the code from the body where the slider is set:

        <div id="slides">
        <img src="images/flash1.png">
        <img src="images/flash2.png">
        <img src="images/flash3.png">
          <a href="#" class="slidesjs-previous slidesjs-navigation"><i class="icon-chevron-left icon-large"></i></a>
          <a href="#" class="slidesjs-next slidesjs-navigation"><i class="icon-chevron-right icon-large"></i></a>
        </div>
    <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
    <script src="js/jquery.slides.js"></script>
    <script>
    $(function(){
      $("#slides").slidesjs({
        play: {
          active: true,
          effect: "slide",
          interval: 5000,
          auto: true,
          swap: true,
          pauseOnHover: true,
          restartDelay: 2500,
          width:936,
          height:247
        }
      });
    });
    </script>
    

    Thanks!

    • tymeJV
      tymeJV about 11 years
      I see all these jQuery plugins...are you loading jQuery anywhere?
    • Kevin B
      Kevin B about 11 years
      Move your jquery.js include to above the rest of your scripts, they need it too.
  • user2266675
    user2266675 about 11 years
    I added <script type="text/javascript" src="code.jquery.com/jquery-latest.min.js"></script> to the top of the scripts and got this error: Uncaught TypeError: Cannot read property 'msie' of undefined jquery.fancybox-1.3.4.pack.js:18 Uncaught TypeError: Object [object Object] has no method 'sticky' index.html:47
  • Kevin B
    Kevin B about 11 years
    msie is supported in 1.9, $.browser isn't.
  • user2266675
    user2266675 about 11 years
    Still getting an error, but we're getting closer! 'Uncaught TypeError: Object [object Object] has no method 'sticky' index.html:52 (anonymous function) index.html:52 o jquery-1.7.2.min.js:2 p.fireWith jquery-1.7.2.min.js:2 e.extend.ready jquery-1.7.2.min.js:2 c.addEventListener.B jquery-1.7.2.min.js:2'
  • Brad M
    Brad M about 11 years
    The js file that creates the sticky method isn't loading, or you are trying to use that method before loading that file.