Nikita Dayneko
Nikita Dayneko

Reputation: 17

generic parameter to function c#

Good day! Can't understand why do compiler highline it as error. Could somebody tell me "why". What do I wrong? So, I have one generic class

    public abstract class SimpleElement<TDataIndexer> where TDataIndexer:IDataIndexator 
{
    public TDataIndexr[] po_registr;
    protected Update updateDelegate;
}

Also, I have delegate, which dealing with updating visual component

public delegate object Update(IDataIndexator[] regs);

My delegate requires parameter type IDataIndexer. How I can pass generic parameter to that delegate?

public delegate object Update(IDataIndexator[] regs);
public abstract class SimpleElement<TDataIndexer> where TDataIndexer:IDataIndexator 
    {
        public TDataIndexr[] po_registr;
        protected Update updateDelegate;
        public function foo(){
            this.updateDelegate(po_registr); // here is error that parameter should be IDataIndexator[], but not TDataIndexer[]
        }
    }

Upvotes: 0

Views: 81

Answers (3)

Jamiec
Jamiec

Reputation: 136174

In order for what you think should happen automatically to work, your TDataIndexer must be constrained to a class

public abstract class SimpleElement<TDataIndexer> 
    where TDataIndexer:class, IDataIndexator 
{ ...}

Live example: http://rextester.com/KDI86395

Upvotes: 2

bruno.almeida
bruno.almeida

Reputation: 2896

Try use .Cast

public interface IDataIndexator { }

public delegate object Update(IDataIndexator[] regs);
public abstract class SimpleElement<TDataIndexer> where TDataIndexer : IDataIndexator
{
    public TDataIndexer[] po_registr;
    protected Update updateDelegate;
    public void foo()
    {
        this.updateDelegate(po_registr.Cast<IDataIndexator>().ToArray()); // here is error that parameter should be IDataIndexator[], but not TDataIndexer[]
    }
}

Upvotes: 1

Gerino
Gerino

Reputation: 1983

The fact that TDataIndexr : IDataIndexator doesn't mean that TDataIndexr[] is IDataIndexator[] in the eyes of the compiler.

Create IDataIndexator[] or do this.updateDelegate(po_registr.Cast<IDataIndexator>().ToArray());.

Basically in a way the system expects to get a parameter of type Array<IDataIndexator>, you are passing Array<SomeType>, where typeof(SomeType) != typeof(IDataIndexator). Therefore for the compiler typeof(Array<IDataIndexator>) != typeof(Array<SomeType>) and error is produced.

Upvotes: 0

Related Questions