Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use <T> in class properties declare in C#

Tags:

c#

I have a class like this

public class Tbl
{
    public string Name {get; set}
    public anyClass Datasource {get; set;} //I don't know what to use there
}

//Usage:
List<anyClass> anyList = GetList(); // Assuming I had a list
Tbl Table = new Tbl();
Table.Name = "Table1";
Table.Datasource = anyList;

Here, my propblem is making the Datasource can accept any input Class. How can I declare the Datasource for Tbl class right way?

Thanks very much

like image 714
akari Avatar asked Jul 27 '10 07:07

akari


People also ask

What is the properties of a class?

The collection of properties assigned to a class defines the class. A class can have multiple properties. For example, objects classified as computers have the following properties: Hardware ID, Manufacturer, Model, and Serial Number.

Why we use get set property in C#?

It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter. The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property.

Where the properties can be declared in C sharp?

A property can be declared inside a class, struct, Interface.

What are properties in class give example?

Properties do not name the storage locations. Instead, they have accessors that read, write, or compute their values. For example, let us have a class named Student, with private fields for age, name, and code.


2 Answers

If it was Tbl<T>, you might choose to expose IList<T> as the DataSource:

public class Table<T>
{
    public string Name {get; set}
    public IList<T> DataSource {get; set;}
}

For non-generic data you might choose to use the non-generic IList; however, in the core framework it is fairly routine to use object as a DataSource, as this allows use of both IList and IListSource (an abstraction around obtaining a list).

like image 187
Marc Gravell Avatar answered Oct 13 '22 05:10

Marc Gravell


You use the type Object:

public object Datasource { get; set; }

If you want to use generics to specify the type:

public class Tbl<T> {
  public string Name { get; set }
  public T Datasource { get; set; }
}
like image 44
Guffa Avatar answered Oct 13 '22 05:10

Guffa