C# Noob: Calling base class constructor

  • Thread starter Thread starter Richard Coltrane
  • Start date Start date
R

Richard Coltrane

Hi there,

In vb.net, if i inherit from a class then the first i generally do in a sub
classes contructor is MyBase.New(..);
Whats the pattern in C#? It seems to do these things automatically; I didn't
think C# did "anything" automatically?

Thanks

Richard
 
In vb.net, if i inherit from a class then the first i generally do in a sub
classes contructor is MyBase.New(..);
Whats the pattern in C#?

The syntax is

public YourClass(...) : base(...)
{
}

It seems to do these things automatically; I didn't
think C# did "anything" automatically?

It only calls a parameterless constructor automatically. If you want
to use one with parameters you have to write the code for it.


Mattias
 
Richard Coltrane said:
In vb.net, if i inherit from a class then the first i generally do in a
sub classes contructor is MyBase.New(..);
Whats the pattern in C#? It seems to do these things automatically; I
didn't think C# did "anything" automatically?

In C# (and many other OOP languages), the default constructor for base
classes is always called automatically. You can use the ": base(...)"
syntax after the constructor declaration in a derived class if you need
access to a base constructor (from the immediate-ancestor class only) with a
specific parameter list.

Had I done any OOP in VB.NET I would have been very surprised to find that
it *didn't* do that. So I guess it all just depends on your perspective.
:)

Pete
 
Richard Coltrane said:
In vb.net, if i inherit from a class then the first i generally do in a sub
classes contructor is MyBase.New(..);
Whats the pattern in C#? It seems to do these things automatically; I didn't
think C# did "anything" automatically?

Others have answered your immediate question, but see
http://pobox.com/~skeet/csharp/constructors.html for more information.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top