Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying '==' operator to generic parameter [duplicate]

Tags:

c#

.net

generics

Possible Duplicate:
Can’t operator == be applied to generic types in C#?

I have a DatabaseLookup{} class where the parameter T will be used by the lookup methods in the class. Before lookup, I want to see if T was already looked up with something like

if (T == previousLookupObject) ...

This doesn't compile at all. What is preventing me from making a simple comparison like this?

like image 303
Teoman Soygul Avatar asked Apr 15 '11 21:04

Teoman Soygul


3 Answers

T is the type parameter. If your previousLookupObject is an object of Type, you need to do typeof(T) == previousLookupObject.

If previousLookupObject is variable of type T, you need to have an actual object of T to compare it to.

If you want to find out if previousLookupObject is of type T, you need to use the is operator: if (previousLookupObject is T).

like image 133
Femaref Avatar answered Nov 17 '22 12:11

Femaref


T is type, previousLookupObject is (I suppose) an object instance. So you are comparing apples to oranges. Try this:

if (previousLookupObject is T)
{
    ...    
}
like image 44
Darin Dimitrov Avatar answered Nov 17 '22 14:11

Darin Dimitrov


Refer to the following links:

Can't operator == be applied to generic types in C#?

c# compare two generic values

like image 1
Akram Shahda Avatar answered Nov 17 '22 14:11

Akram Shahda