7

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?

Community
  • 1
  • 1
Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • 3
    Is `T` referring to the generic type or an actual variable of the generic. `T` is usually used as the name of the generic type. Not an object but a type. Try defining a variable of type `T`. – Chad La Guardia Apr 15 '11 at 21:21
  • 2
    And then use `thisObject.Equals(previousLookupObject)` instead of `==` – H H Apr 15 '11 at 21:26

4 Answers4

16

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).

Femaref
  • 60,705
  • 7
  • 138
  • 176
8

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

if (previousLookupObject is T)
{
    ...    
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

Refer to the following links:

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

c# compare two generic values

Community
  • 1
  • 1
Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
0

What type is previousLookupObject? Generic type parameters are types, and can't be used as normal object references.

recursive
  • 83,943
  • 34
  • 151
  • 241