Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Generic list question
Message
From
19/11/2014 07:49:21
 
General information
Forum:
ASP.NET
Category:
Other
Environment versions
Environment:
C# 5.0
OS:
Windows 7
Network:
SAMBA Server
Database:
MS SQL Server
Application:
Desktop
Miscellaneous
Thread ID:
01611163
Message ID:
01611164
Views:
65
>Hi All, I need to declare a generic list of a type which is decided at runtime, the type is one of several classes that all implement a common interface , I'm unsure how to do this, at first I thought I could use the Type of the class to create a list but this is not so - a small example of what I mean is shown below
>
>
>
>IMyInterFace  i = GetClassType();
>
>List<i> mylist = new List<i>();
>
>
>IMyInterFace GetClassType()
>{
>  if(SomeCondition)
>    return ClassA;
>  else
>    return classB;
>}
>
Think you have to cast to the interface, Pete

This compiles
	static class Test_GenericInterface
	{
		internal static void Go()
		{
			List<ITest> theList = new List<ITest>();

			theList.Add(GetElement(true));
		}
		static ITest GetElement( bool isFirst)
		{
			if (isFirst)
				return (ITest)(new ClassA());
			else
				return (ITest)(new ClassB());

		}
	}

	interface ITest
	{
		int Get();
	}
	class ClassA : ITest
	{
		public int Get()
		{
			return 1;
		}

	}
	class ClassB : ITest
	{
		public int Get()
		{
			return 3;
		}
	}
}
Gregory
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform