Test null value in generic

  • Thread starter Thread starter Giorgio Parmeggiani
  • Start date Start date
G

Giorgio Parmeggiani

HI

I have a method that receive a generic parameter and also return a generic:
public T GetById(ID id)

I've want to return null if the received parameter is null, so i have write
this code:
public T GetById(ID id)
{
if(id == default(ID))
return default(T)
...................
}

But during compilation i receive an exception that tell me that is not possible
to apply operator == at parameter of type ID and ID

How can i solve my problem?

Thank in advance
Giorgio
 
Giorgio Parmeggiani said:
I have a method that receive a generic parameter and also return a generic:
public T GetById(ID id)

I've want to return null if the received parameter is null, so i have write
this code:
public T GetById(ID id)
{
if(id == default(ID))
return default(T)
...................
}

But during compilation i receive an exception that tell me that is not possible
to apply operator == at parameter of type ID and ID

How can i solve my problem?

Is ID always a reference type? If so, make that a constraint and you
should be able to compare against null directly.
 
Hi

Thank for your reply
Is ID always a reference type? If so, make that a constraint and you
should be able to compare against null directly.

The ID can be an value type or also a reference type.
How can i create a constraint?

Thank
Giorgio
 
"Giorgio Parmeggiani" <[email protected]> a écrit dans le message de
news: (e-mail address removed)...

| The ID can be an value type or also a reference type.
| How can i create a constraint?

You cannot, but you can test against default(T) instead of null, since value
types cannot be set to null. Take a look at IEquatable, implemented by the
majority of value types and also by some reference types.

Joanna
 

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