Grasshopper
Grasshopper

Reputation: 3

Subset of Generic Abstract List - C#

I am making some abstract base classes. The base object is defined as:

    public abstract class Bar
    {
        public bool Enabled;
    }

The base collection is defined as:

 public abstract class Foo<T> : List<T>
        where T : Bar
    {
        public Foo<T> GetAllEnabled()
        {
            Foo<T> ret = new Foo<T>();

            foreach (T item in this)
            {
                if (item.Enabled)
                {
                    ret.Add(item);
                }
            }

            return ret;
        }
    }

Naturally, I get an error trying do create a new Foo<T>(), because Foo is an abstract class. Without the abstract modifier, everything works fine, but I want the modifier there because I want to make sure the class gets derived.

I have tried

     Type U = this.GetType();
        Foo ret = new U();
but I get an error "The type or namespace name 'U' could not be found (blah blah blah)".

I think my attempted fix should work, and I must just have the syntax wrong. What am I missing here?

Upvotes: 0

Views: 882

Answers (4)

Anthony Pegram
Anthony Pegram

Reputation: 126932

Type U = this.GetType();
Foo ret = new U();

Type U will contain information on the data type, it is not the equivalent of a generic type parameter that you can then instantiate. You can use U to create a type through Activator.CreateInstance, which has a few overloads and accepts Type objects, but then you're left with needing to cast the resulting object to an appropriate type in order to be able to use it.

Type type = this.GetType();
Foo<T> ret = (Foo<T>)Activator.CreateInstance(type);

Upvotes: 2

Euphoric
Euphoric

Reputation: 12849

And what type do you want to create? What are you actualy trying to acomplish? Why are you forcing to derive from your collection class? You dont need collection to be abstract, if you want its items to be abstract. Especialy with generics.

Also : http://blogs.msdn.com/b/codeanalysis/archive/2006/04/27/585476.aspx (I think there is much better article, but I cant find it)

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273484

Of course it is an error to instantiate the abstract class Foo<T>. That is a direct consequence of being abstract.

but I want the [abstract] modifier there because I want to make sure the class gets derived.

Then derive it first, class Foo2<T> : Foo<T> { } and then instantiate Foo2<T>.

Upvotes: 1

Waleed Al-Balooshi
Waleed Al-Balooshi

Reputation: 6406

but I want the modifier there because I want to make sure the class gets derived.

As per your own words, you will need to derive a class that you can then instantiate.

Upvotes: 1

Related Questions