Xaqron
Xaqron

Reputation: 30887

How to get the type of derived class at base class without generics?

My base class use reflection on derived classes to provide some functionality to them. Currently I do it this way:

abstract class BaseClass<T>
{
    string GetClassString()
    {
        // Iterate through derived class, and play with it's properties
        // So I need to know the type of derived class (here T).
        return result;
    }

    static bool TryParse(string classString, out T result)
    {
        // I should declare a variable as T and return it
    }
}

Can I do this without generics ?

Upvotes: 0

Views: 943

Answers (1)

J.N.
J.N.

Reputation: 8431

Edit:

Sorry, you want the type parameter (ie typeof(T)). In that case you still use this.GetType() but you add .GetGenericArguments()[0] after.

Try parse: You need to create a new instance of a type you don't know

There are two ways: First, without changing the rest, with the Activator class and the following code:

result = (T) Activator.CreateInstance(typeof(T))

(MSDN).

Then, you could add a "new" constraint to your type:

MyClass<T> where T : new() {...}
result = new T();

Both samples require parameter less constructors. If you want to pass parameters, then you need to go deeper inside System.Reflection, get the list of constructors and call the one you want. A factory pattern may also do the job.

Upvotes: 4

Related Questions