|
-
Jan 23rd, 2009, 04:24 PM
#1
Thread Starter
Frenzied Member
[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?
-
Jan 24th, 2009, 03:38 PM
#2
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;
-
Jan 24th, 2009, 05:37 PM
#3
Thread Starter
Frenzied Member
Re: [2.0] Return 2 types with generic parameters?
 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.
-
Jan 25th, 2009, 08:19 AM
#4
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.
-
Jan 26th, 2009, 06:57 PM
#5
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.
-
Jan 26th, 2009, 09:46 PM
#6
Thread Starter
Frenzied Member
Re: [2.0] Return 2 types with generic parameters?
I guess you guys are right, thanks.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|