MSL MSL - 1 year ago 130
C# Question

Null value for generic class

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

is a wrong value, I am returning
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

what should I do?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download