hamidovt
asked on
Using generics in C# ASP .Net 2.0
Hi,
I am using trying to use List of <T> generics in C# ASP.NET 2.0. In my code I have a a method that returns a list of objects with the following definition. Something like
public static List<Location> GetAll()
List<Location> locations = new List<Location>();
...
return locations;
}
This part of using generics is OK. My problem is that I would like to pass a List of <T> to another method. The code would look something like this
protected string Locations(List<Location> locations)
{
string locationsString = string.Empty;
foreach(Location lc in locations)
{
locationsString += lc.Name + " ";
}
return locationsString;
}
However I eceive a compilation error saying that type or namespace name 'List' could not be found.
My questions are:
- is it possible to path a List<T> ?
- what is the right syntax to do that in C# ?
Thanks in advance!
I am using trying to use List of <T> generics in C# ASP.NET 2.0. In my code I have a a method that returns a list of objects with the following definition. Something like
public static List<Location> GetAll()
List<Location> locations = new List<Location>();
...
return locations;
}
This part of using generics is OK. My problem is that I would like to pass a List of <T> to another method. The code would look something like this
protected string Locations(List<Location> locations)
{
string locationsString = string.Empty;
foreach(Location lc in locations)
{
locationsString += lc.Name + " ";
}
return locationsString;
}
However I eceive a compilation error saying that type or namespace name 'List' could not be found.
My questions are:
- is it possible to path a List<T> ?
- what is the right syntax to do that in C# ?
Thanks in advance!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
....
protected string Locations<T>(List<T> locations) where T : IWithName
{
string locationsString = string.Empty;
foreach(T lc in locations)
{
locationsString += lc.Name + " ";
}
return locationsString;
}
public interface IWithName
{
}
protected string Locations<T>(List<T> locations) where T : IWithName
{
string locationsString = string.Empty;
foreach(T lc in locations)
{
locationsString += lc.Name + " ";
}
return locationsString;
}
public interface IWithName
{
}
public interface IWithName
{
string Name
{get; set;}
}
... and all the classes that are used as T are implementing IWithName . Is that what you want?
{
string Name
{get; set;}
}
... and all the classes that are used as T are implementing IWithName . Is that what you want?
ASKER
You are indeed right, actually I have missed the using System.Collections.Generic ....
ASKER