Monday, June 7, 2010

Calling Base Constructor from Child Class Constructor

Whenever we are writing logic for constructor of a class, the first statement in that code block should call a constructor of base class. If not we will get following error –

First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class 'base class name' of 'class name' does not have an accessible 'Sub New' that can be called with no arguments.

Example:

         1:     
         2:   Public Sub New()    
         3:     
         4:   Dim l_instanceContext As New System.ServiceModel.InstanceContext(New DuplexSvcClientCallback)    
         5:   Dim l_PollingDuplexHttpBinding As New PollingDuplexHttpBinding    
         6:   Dim l_EndpointAddress As New EndpointAddress("http://localhost/MyDuplexService/DuplexSvc.svc")    
         7:   MyBase.New(l_instanceContext, l_PollingDuplexHttpBinding, l_EndpointAddress)    
         8:     
         9:   End Sub    

This is wrong and will give above error message.

The logic can be corrected by calling base constructor as first statement –

         1:     
         2:   Public Sub New()    
         3:     
         4:   MyBase.New(    
         5:          New System.ServiceModel.InstanceContext(New DuplexSvcClientCallback),    
         6:          New PollingDuplexHttpBinding,    
         7:          New EndpointAddress("http://localhost/MyDuplexService/DuplexSvc.svc")    
         8:          )    
         9:   End Sub    

Note that the base constructor call is the first statement and you have all the logic implemented in it.

You can even write your logic in a shared/static method and call from first statement as follows:

         1:     
         2:   Public Sub New()    
         3:     
         4:   MyBase.New(GetInstanceContext(), New PollingDuplexHttpBinding,    
         5:   New EndpointAddress("http://localhost/MyDuplexService/DuplexSvc.svc"))    
         6:     
         7:   End Sub    
         8:     
         9:   Private Shared Function GetInstanceContext() As System.ServiceModel.InstanceContext    
        10:     
        11:   Return New System.ServiceModel.InstanceContext(New DuplexSvcClientCallback)    
        12:     
        13:   End Function    

Note:

While writing constructor, if no base class constructor is explicitly called, then the default constructor of base class (constructor without arguments) will be called.

If base class lacks default constructor, then writing child class without explicitly calling base class constructor will cause the error mentioned

No comments:

Post a Comment