Default accessors in Collection classes

A

Andy B

I have a class called ContractDefinitions which is a property of another
class. It is a collection of Definition types. When I created an instance of
ContractDefinitions and added 2 Definition objects to it, The compiler
complained telling me that I had to create a default accessor for the
ContractDefinitions collection class. How do you do this? I am trying to
save the classes with the XmlSerializer class.
 
M

Marc Gravell

Can you post the exact message? I expect it actually asked for a
default constructor - i.e. a public, parameterless constructor - i.e.
the second one here:

public class ContractDefinitions : Collection<Definition> {
public ContractDefinitions(int foo) { }
public ContractDefinitions() { }
}

Normally (for a concrete class) the C# compiler creates a default
constructor for you automatically. If you add any (non-static)
constructor yourself, then it doesn't do this - so you need to add the
parameterless constructor too (if you want it).

Marc
 
M

Morten Wennevik [C# MVP]

Hi Andy,

Are you creating the ContractsDefinitions class by inheriting some other
class? If this other class does not have a default constructor your own
class won't have one either. The default constructor is the parameterless
constructor which is added by the compiler if no other constructors are
defined, but if another constructor exists, the compiler won't add the
default constructor.

// Default constructor of MyClass
public MyClass()
{
}
 

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

Top