[RESOLVED] [2.0] Return 2 types with generic parameters?
Code:
public class RoomCollection : List<Room>
{
public T IndexOfName<T>(string name)
{
if (!(typeof(T) == typeof(int)) && !(typeof(T) == typeof(Room)))
throw new Exception("Invalid generic parameter!");
for (int i = 0; i < this.Count; i++)
{
if (this[i].SiteID == name)
{
if (typeof(T) == typeof(int))
return (T)(object)i;
return (T)(object)this[i];
}
}
if (typeof(T) == typeof(int))
return (T)(object)-1;
return (T)(object)null;
}
}
I want to easily be able to choose what it returns so I made this. How do you properly do this?
Re: [2.0] Return 2 types with generic parameters?
I have a generic class that returns objects of type T, it is something like
Code:
public class RoomCollection<T>
{
public List<T> IndexOfName(string name)
{
//codes
return null;
}
}
Does that make a difference on your current implementation?
Sampe usage would be
Code:
private static RoomCollection<Room> _rooms = null;
Re: [2.0] Return 2 types with generic parameters?
Quote:
Originally Posted by dee-u
I have a generic class that returns objects of type T, it is something like
Code:
public class RoomCollection<T>
{
public List<T> IndexOfName(string name)
{
//codes
return null;
}
}
Does that make a difference on your current implementation?
Sampe usage would be
Code:
private static RoomCollection<Room> _rooms = null;
Yes, I allow the user of the class to choose between 2 returns. if they pass int as the generic parameter it returns the index. If they pass Room it returns the object instead of the index.
Re: [2.0] Return 2 types with generic parameters?
Create two different methods, one that accepts an int and one that accepts a 'Room'. This way, you're not hacking a single method to do two things, but have two methods, each of which does exactly what it says.
Re: [2.0] Return 2 types with generic parameters?
As mendhak suggests, that method is a complete hack. The name of the method is "IndexOfName", so there's no way that method should be returning an item. It should ONLY be returning an index of an item, which MUST be an int. You should have a completely separate method that returns an item by name.
Also, if you want to retrieve items by name then you should probably be using a Dictionary, not a List. That's no good if the names aren't unique, of course.
Re: [2.0] Return 2 types with generic parameters?
I guess you guys are right, thanks.