venter venter - 16 days ago 6
C# Question

Getting a null reference while using GetElementType()

I'm trying to make my graphQL mutation generic. But on runtime i get an error.
The error says: Object reference not set to an instance of an object.

public class ApplicationMutation<T> : ObjectGraphType where T: BaseModel
{
public ApplicationMutation()
{
this.Name = "RootMutation";

var nameofT = typeof(T).GetElementType().Name;

this.Field<AddPayloadType<T>>(
"add" + nameofT,
arguments: new InputQueryArguments<AddInputType<T>>(),
resolve: context =>
{
var input = context.GetArgument<AddInput<T>>("input");

var result = Activator.CreateInstance<T>();
{
Name = "1337 p40c355I73m";
};

return new AddPayload<T>(input, result);
});

this.Field<UpdatePayloadType<T>>(
"update" + nameofT,
arguments: new InputQueryArguments<UpdateInputType<T>>(),
resolve: context =>
{
var input = context.GetArgument<UpdateInput<T>>("input");

var result = Activator.CreateInstance<T>();
{
Name = "rul0r item";
};

return new UpdatePayload<T>(input, result);
});

this.Field<DeletePayloadType<T>>(
"delete" + nameofT,
arguments: new InputQueryArguments<DeleteInputType<T>>(),
resolve: context =>
{
var input = context.GetArgument<DeleteInput<T>>("input");

var result = true;

return new DeletePayload<T>(input, result);
});
}
}


The exception is thrown from the following line:
var nameofT = typeof(T).GetElementType().Name;



If more information is required, just ask for it.

Answer

You can only use the GetElementType() for arrays, pointers and references types..

null if the current Type is not an array or a pointer, or is not passed by reference, or represents a generic type or a type parameter in the definition of a generic type or generic method https://msdn.microsoft.com/en-us/library/system.type.getelementtype.aspx

It will return null for generic's