Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Instance of a C# Generic Class

The title is possibly worded incorrectly, so please show me the correct terms.

I've got a base class called DAL_Base that accepts a generic type T. The type T comes from our many classes in our Business Objects layer, and each one of them has a corresponding Data Access Layer.

DAL_Base accepts parameters that allows me to specify the Stored Procedure names and parameters that I use to call methods to select, insert, and update records.

What I currently seem to be stuck on is that I can't seem to find a way to instantiate a new instance of my DAL_Base, which needs to initialize the various variables.

Partial listing:

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
  }

}

The error VS2010 is giving me is:

Invalid token '(' in class, struct, or interface member declaration

I have tried creating constructors without parenthesis, but that is not useful either.

When I search, all I seem to be able to return are ways to create instances of my generic type T. That was easy to find out how to do!

MSDN's An Introduction to C# Generics did not seem to cover this, either.

like image 468
jp2code Avatar asked Feb 13 '13 17:02

jp2code


1 Answers

You should not have angle brackets (< and >) on the constructor.

public class DAL_Base<T> where T : IDisposable, new()
{
    public DAL_Base()
    {
    }
}
like image 175
Paul Ruane Avatar answered Oct 11 '22 18:10

Paul Ruane