I have a Generic Proxy Class contains T type object That is also a class. i wants to create a object of T.
class Proxy<T>: IClient
{
T _classObj;
public Proxy()
{
this._classObj = //create new instance of type T
}
}
I have a Generic Proxy Class contains T type object That is also a class. i wants to create a object of T.
class Proxy<T>: IClient
{
T _classObj;
public Proxy()
{
this._classObj = //create new instance of type T
}
}
You can either use the default value for that type (which will be null
for reference types, or one of these for value types: Default Values Table)
_classObj = default(T);
Or apply the new()
generic constraint, that forces the type T
to have the default parameterless constructor
class Proxy<T>: IClient where T: new()
{
T _classObj;
public Proxy() {
_classObj = new T();
}
}
If T
is a class and it guarantees that it has a new()
operator:
class Proxy<T> : IClient where T : class, new() {
T _classObj;
public Proxy() {
this._classObj = new T();
}
}
otherwise, or if T
is a struct
, so you can do:
class Proxy<T>: IClient where T : struct {
T _classObj;
public Proxy() {
this._classObj = default(T); // which will be null for reference-types e.g. classes
}
}
UPDATE:
For call a method on T
there is some different situations. But, according to question and comments, I assume that T
is a class
and it has a new()
operator. Also, it implements the IGetDataImplementer
which has a method named GetData
. So we can:
interface IGetDataImplementer{
object GetData();
}
class Proxy<T> : IClient where T : class, IGetDataImplementer, new() {
T _classObj;
public Proxy() {
this._classObj = new T();
var data = this._classObj.GetData();
}
}