Stewart Alan
Stewart Alan

Reputation: 1643

How can I set a Class Public Property as Type List<T>?

I want to define a public property in a User Control with a type of List that I can pass a List to and then have the control bind it to a repeater.

public partial class RepeaterPager : System.Web.UI.UserControl
{
    public List<T> DataSource;
}

The from calling code

List<someClass> list = new List<someClass>;
RepeaterPager1.DataSource = list ;

I thought this would be simple, but I am getting Error The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) on the line that declares the public property. What am I doing wrong

Cheers

Stewart

Upvotes: 1

Views: 1175

Answers (4)

TheSean
TheSean

Reputation: 4566

The general pattern for this type of data binding is to define DataSource as type object. Then, in the set method you can do a runtime check to verify the object is of a type you expect -- throw an exception or debug assert otherwise.

Besides, Repeater.DataSource is type object anyways ...

Many times I can get away without holding a reference to the datasource, so I pass it directly to the control:

public object DataSource
{
    get { return myRepeater.DataSource; }
    set {
        if (value is IEnumerable) // or whatever your requirement is, if needed
            myRepeater.DataSource = value;
        else
            throw new NotSupportedException("DataSource must be an IEnumerable type");
    }
}

However, if you really do need to know about the type T, I would consider the following:

  1. If possible, use the generic class idea others have suggested.
  2. If you need to repeat this pattern for different classes, build a base class or Interface for all your data sources to derive from
  3. Use DataSource as type object, but just grab the type at run time using obj.GetType(). (Depending on your needs this may or may not work)

Upvotes: 0

Leonard Br&#252;nings
Leonard Br&#252;nings

Reputation: 13242

You either need to define generic Type, or make RepeaterPager generic

public partial class RepeaterPager<T> : System.Web.UI.UserControl
{
    public List<T> DataSource;
}

Upvotes: 0

Anton Gogolev
Anton Gogolev

Reputation: 115749

This is only possible if the class containing property is generic. In theory, you could use generic method:

void SetDataSource<T>(List<T> dataSource)

but you'll lose type information elsewhere.

Maybe,

IEnumerable DataSource

will be a better option?

Upvotes: 2

George Duckett
George Duckett

Reputation: 32428

You can't have generic parameters in fields of a class with out the class being generic.

See this answer for info on making a usercontrol generic: C# generics usercontrol

Or you could just use a non-generic version, such as IEnumerable or IList.

Upvotes: 1

Related Questions