Generics and returning class objects
I am trying to return an object of a class using the generics.
This is the generic class
public class ClientBase <S>
{
protected S CreateObject()
{
return default(S) ;
}
}
This is how I am trying to use it...
public class ClientUser : ClientBase <SomeClass>
{
public void call()
{
var client = this.CreateObject();
client.SomeClassMethod();
}
}
While I get the SomeClassMethod()
in the client object, when running the code it gives an error at the line:
client.SomeClassMethod();
Error is 'Object reference not set to an instance of an object'. I know there is something missing in the generic class ClientBase's CreateObject() method; just cant figure that bit out. Could someone help me here please?
Thanks for your t开发者_高级运维ime...
default(S)
where S
is a reference type is null. In your case, default(SomeClass)
returns null. When you try to invoke a method on a null reference, that's when you get your exception.
Are you trying to return a default instance of SomeClass
? You may want to use a new()
constraint and return new S()
in your generic class instead, like so:
public class ClientBase<S> where S : new()
{
protected S CreateObject()
{
return new S();
}
}
If S
needs to be a reference type you can also constrain it to class
:
public class ClientBase<S> where S : class, new()
{
protected S CreateObject()
{
return new S();
}
}
See what default(T)
does: http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx
In your case, default(S)
is going to return null (because it's a class) - this is not an instance of the class.
You either need to call new S()
or some other S
constructor or override CreateObject
in your derived class.
精彩评论