Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a Generic List property in a static class

Tags:

c#

list

generics

I need to use a static class to hold some simple values during runtime:

public static class Globals
{
    public static string UserName
    { get; set; }

     ...more properties
}

I now have need to store a List of objects - typed according to classes I have defined. This List will be re-used for different Object types, and so I thought to define it as Generic.
This is where I am stuck: how do I define a property inside a static class that will be containing different types of Lists at different times in the applications execution?

Needs to be something like :

    public List<T> Results {get; set;}
like image 976
callisto Avatar asked Dec 14 '12 09:12

callisto


1 Answers

You need to define your class as a Generic class.

public static class Globals<T>
{
    public static string UserName
    { get; set; }
    public static List<T> Results { get; set; }

}

later you can use it like:

Globals<string>.Results = new List<string>();

Also your property Results needs to be private. You may consider exposing your methods to interact with the list, instead of exposing the list through a property.

See: C#/.NET Fundamentals: Returning an Immutable Collection

like image 168
Habib Avatar answered Sep 28 '22 08:09

Habib