Default accessors in Collection classes

  • Thread starter Thread starter Andy B
  • Start date Start date
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.
 
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
 
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()
{
}
 
Back
Top