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 time…
default(S)whereSis 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 anew()constraint andreturn new S()in your generic class instead, like so:If
Sneeds to be a reference type you can also constrain it toclass: