2

I have a class like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindowsFormsApplication1
{
    public class MyList<T> : List<T>
    {
        public int SelectedIndex { get; set; }

        public T CurrentItem
        {
            get
            {
                if (this.SelectedIndex > this.Count)
                    return null;

                return this[this.SelectedIndex];
            }
        }
    }
}

I am creating a class that derive from list and create a property for getting the current item.

If SelectedIndex is a wrong value, I am returning null but it has an error

Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead.

I want the return value to be null not default(T).

what should I do?

Balagurunathan Marimuthu
  • 2,927
  • 4
  • 31
  • 44
MSL
  • 990
  • 1
  • 12
  • 28
  • 1
    If you want it to be able to return `null` then you would either need to make it a nullable type, or place a constraint on T to make it a reference type by using `T : class`. – Evan Trimboli Nov 09 '16 at 11:15
  • What will be T in your case ? – mybirthname Nov 09 '16 at 11:17
  • What do you think `default(T)` is? For reference-types this evaluates to `null`. For value-types (e.g. `int`) this is either zero or whatever the types default-type is. – MakePeaceGreatAgain Nov 09 '16 at 11:21
  • Might-be-interesting-to-read: http://stackoverflow.com/questions/21692193/why-not-inherit-from-listt/21694054#21694054 – Maarten Nov 09 '16 at 11:22
  • As an alternative, you can consider throwing an `IndexOutOfRangeException` instead of returning null. Well, that would already occur if you just `return this[this.SelectedIndex]`. – Milack27 Nov 09 '16 at 11:25

1 Answers1

3

null is an invalid value for value types such as int or double. Therefore, you have to restrict the generic type parameter to classes like so:

public class MyList<T> : List<T> where T : class

Then, the compiler error will disappear.

Georg
  • 5,626
  • 1
  • 23
  • 44