Kyo Joon Lee
Kyo Joon Lee

Reputation: 1

i implemented generic method which is declared in an interface but I got an error

I declared a generic method in a interface called IDatabase. And I implemented the method in a class named MsSql.cs. But error message says that I didn't implement the method. I don't know what's wrong.

My code is as follows.

in the IDatabase, I declared as follows.

T BeginTransaction<T>(string connectionString);

And in the MsSql.cs, I implemented as follows.

public SqlTransaction BeginTransaction(string connectionString) 
{ 
    tran_con = new SqlConnection(connectionString); 
    tran_con.Open(); 
    SqlTransaction transaction = tran_con.BeginTransaction(); 
    return transaction; 
}

please let me know why the error was occurred.

Upvotes: 0

Views: 75

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

If your interface asks for T, you have to provide a T, not an SqlTransaction, which is in no way related to T at all.

But even if there were a relation between those types you can´t expect the compiler to guess that you want to use SqlTransaction for T. Imagine the following situation. You have an instance of your interface:

IDatabase db = GetDatabaseInstance();

IDatabaseIDatabase does not know anything about the actual underlying type returned by GetDatabaseInstance. So even if you could implement BeginTransaction this way, how should a caller ever infer that type:

db.BeginTransaction(...);  // what should this method return?

The only way here is to make your interface itself generic. Then you´re able to indicate at compile-time what type T is.

Upvotes: 0

Hugo
Hugo

Reputation: 479

That's not how generic methods work. What your interface expects is a method with the same signature. When you use <T> in a method it means that method is generic, not that it can be implemented with any type. To do what you want to do, you could make the interface generic like this for example.

interface IDatabase<T> {
    T BeginTransaction(string connectionString);
}

class MsSql: IDatabase<SqlTransaction> {
    public SqlTransaction BeginTransaction(string connectionString) 
    { 
        tran_con = new SqlConnection(connectionString); 
        tran_con.Open(); 
        SqlTransaction transaction = tran_con.BeginTransaction(); 
        return transaction; 
    }
}

On the other hand, this is what implementing the genric method would look like:

public T BeginTransaction<T>(string connectionString) { 
    // Code that generates any type T based on the connectionString
}

Upvotes: 1

Related Questions