-1

Possible Duplicate:
How do I compare a generic type to its default value?

I have a generic function that needs to test if the object that is passed into it is empty or not. But because its a generic type, the compiler doesnt know if a class or a struct is passed. Because of this I cant test for null I have to test if the type is empty.

    public virtual void SetFocusedObject(T obj)
{
    //since we dont know if T is a class or a struct test against default
    T defaultT = default(T);

    if(obj != defaultT)
    {
        //code      
    }
}

This does not work and its because the compiler doesnt know what T is to be able to compile the test

alternatively I tried the following as well

    public virtual void SetFocusedObject(T obj)
{
    //since we dont know if T is a class or a struct test against empty type
    T defaultT = T.GetConstructor(T.EmptyTypes).Invoke(null);

    if(obj != defaultT)
    {
        //code  
    }
}

And for the same exact reason, this does not work either. I was hoping that someone might suggest a method that will work.

Community
  • 1
  • 1
MichaelTaylor3D
  • 1,615
  • 3
  • 18
  • 32

2 Answers2

1

That is not a generic function. Unless the function is a member of generic class with a type argument named 'T', you need to declare it like this:

public virtual void SetFocusedObject<T>(T obj)

This will allow you to use default(T) successfully:

public virtual void SetFocusedObject<T>(T obj)
{   
    if (obj.Equals(default(T))) return;

    //code      
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

If by empty referece object you mean null and when you compare struct with null you get false, why not use this as test:

    public static void Test<T>(T obj)
    {
        if (obj == null) // default refernce type (which is null)
        {
            Console.WriteLine("default!");
        }
        else if(obj.Equals(default(T))) // default value types
        {
            Console.WriteLine("default!");
        }
    }
    public static void Main()
    {
        object o = null;
        Test(o); // test detects default
        Test(0); // test detects default
        Class1 c = new Class1();
        Test(c); // test does not detect default
    }

Though I'm not sure if you consider null default value for reference type, or whether you want to know if default reference type instance is the one created by default constructor.

Bartosz
  • 3,318
  • 21
  • 31