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?
nullthen you would either need to make it a nullable type, or place a constraint on T to make it a reference type by usingT : class.default(T)is? For reference-types this evaluates tonull. For value-types (e.g.int) this is either zero or whatever the types default-type is.IndexOutOfRangeExceptioninstead of returning null. Well, that would already occur if you justreturn this[this.SelectedIndex].