Let's say we have a class that looks like this:
public class Repository<T>
{
private readonly string _connectionString;
public Repository(string connectionString)
{
_connectionString = connectionString;
}
void T SomeMethod()
{
// do work here
return T;
}
}
In the case above, the Type would need to be declared along with the class, but you would not need to specify the Type when calling SomeMethod()
.
Or, you could also do this:
public class Repository
{
private readonly string _connectionString;
public Repository(string connectionString)
{
_connectionString = connectionString;
}
void T SomeMethod<T>()
{
// do work here
return T;
}
}
In this case, the class would be created without a Type, but you would need to declare the Type when calling SomeMethod()
.
Without a total duplication of all code, how would one create the same class so that the Type was optional when creating it? In other words, I'd like both of these to work upstream:
Repository<MyType> repo = new Repository<MyType>();
var something = repo.SomeMethod();
and
Repository repo = new Repository();
var something = repo.SomeMethod<MyType>();