Create C # Class Instance

The name may not be spelled correctly, so please show me the correct conditions.

I have a base class DAL_Base that accepts a generic type T. A type Tcomes from our many classes at our Business Objects level, and each of them has an appropriate level of data access.

DAL_Base accepts parameters that allow me to specify the names and parameters of the stored procedure that I use to call methods to select, insert, and update records.

What I'm delaying right now is that I cannot find a way to create an instance of a new instance of my DAL_Base , which should initialize various variables.

Partial List:

public class DAL_Base<T> where T : IDisposable, new() {

  public DAL_Base<T>() { // <= ERROR HERE
    // initialize items that will be used in all derived classes
  }

}

Error VS2010 gives me:

Invalid token '(' in a member declaration of a class, structure, or interface

I tried to create constructors without parentheses, but this is also not useful.

When I do a search, all I can return is the ways to instantiate my generic type T. It was easy to learn how to do it!

The MSDN Introduction to C # Generics also did not cover this.

+5
source share
3 answers

The constructor should not have angle brackets ( <and >).

public class DAL_Base<T> where T : IDisposable, new()
{
    public DAL_Base()
    {
    }
}
+8
source

You should not have a generic type argument in your constructor:

public class DAL_Base<T> where T : IDisposable, new() {

  public DAL_Base() { // <= this should work
    // initialize items that will be used in all derived classes
  }

}

Since you yourself decorated the class with a type argument, the type is available in the constructor:

  public DAL_Base() {
     var listOfObjects = new List<T>();
  }
+6

public DAL_Base() { // <= NO ERROR HERE :)

, - . , .

+4

All Articles