How do you pass a null argument to a generic method?

  • Thread starter Thread starter Lee Grissom
  • Start date Start date
L

Lee Grissom

public void SomeGenericClassConstructor(T item){}

Very simple question: How do I pass in a null value as the argument?
Generics require something different than what I'm use to.

Thanks,
Lee
 
I think maybe you have to do something like this:

T dummy = default(T);
SomeGenericMethod(dummy);
 
public void SomeGenericClassConstructor(T item){}

Very simple question: How do I pass in a null value as the argument?
Generics require something different than what I'm use to.

If I understand the question correctly, the problem is that if you
just write "null", the compiler can't figure out which version of the
method to call, because null can be any reference type. You can
specify the type explicitly instead:

SomeGenericClassConstructor<string>(null);

Jesse
 
public void SomeGenericClassConstructor(T item){}

Very simple question: How do I pass in a null value as the argument?
Generics require something different than what I'm use to.

I'm not sure that I understand your question.

Do you mean that this is a method within a generic class:

public class SomeGenericClass<T>
{
public void SomeGenericClass(T item) { }
}

? If this is so, then there is no problem passing null to the
constructor. Of course, you have to instantiate the generic class to a
particular class, first:

SomeGenericClass<string> myInstance = new
SomeGenericClass<string>(null);

Or, are you talking about a generic method, in which case I think that
your syntax was wrong:

public void SomeGenericClassConstructor<T>(T item) { }

In that case, you can still pass null as the argument, but you have to
instantiate the method:

SomeGenericClassConstructor<string>(null);

Or was it neither of these?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top