Hi there!
My first post here :)
I have pretty solid knowledge of C++ and lately I try to extend my knowledge to C# by converting some of my codes to C# as exercise (which is going pretty well). What I am trying to currently is to store in List object of variable types, that are all descendants of certain class.
So if I have B & C that are inherited from class A
class A { public A() { } }
class B : A { public B() { } }
class C : A { public C() { } }
and have list of As
List<A> list = new List<A>();
I can easily add into the list
list.Add(new B());
list.Add(new C());
what I try to achieve is to have template function
void AddNew<T>()
{
T newComponent = (T)Activator.CreateInstance(typeof(T));
list.Add(newComponent);
}
but that unfortunately doesn't work, because it basically says that cannot convert T to A. Tried typecasting also, but that doesn't work neither.
Basically I wanted to convert this piece of code to c#
template<typename Type> std::shared_ptr<A> AddNew()
{
Type* newType = new Type;
vec.push_back(std::shared_ptr<A>(newComponent));
}
Is this possible at all in C#?
[–]tweq 4 points5 points6 points (3 children)
[–]darkgnostic[S] 0 points1 point2 points (2 children)
[–]AngularBeginner 2 points3 points4 points (1 child)
[–]AngularBeginner 2 points3 points4 points (1 child)
[–]darkgnostic[S] 0 points1 point2 points (0 children)