Shay Zambrovski
Shay Zambrovski

Reputation: 656

Generic delegate type error

lets say i have the next Course class:

class Course
    {
        internal Student myStudent { get; set; }
        internal string Name { get; set; }

        public override string ToString()
        {
            return string.Format("{0, -5} {1, -15} {2}", Name, myStudent.Name, string.Join(" ", myStudent.Grade));
        }
        internal class Student
        {
            internal string Name { get; set; }
            internal List<int?> Grade { get; set; }
        }
    }

and i want in the main use in a generic delegate, once for int and once for string:

SomeDelegate<string> d1 = new SomeDelegate<string>(course => course.Name);
SomeDelegate<int> d2 = new SomeDelegate<int>(course => (int)course.myStudent.Grade.DefaultIfEmpty(null).Average());

The generic delegate is:

delegate T SomeDelegate<T>(T param);

but i get errors.

string does not contain a definition for 'Name'....

Why is that?

Thanks!

Upvotes: 1

Views: 156

Answers (2)

Berin Loritsch
Berin Loritsch

Reputation: 11463

You'll probably need a pair of delegates. The issue here is that we have two use cases you are wanting to use:

delegate T SomeDelegate<T>(T param);

Above is a simple delegate, which means you are passing in a T, not a lambda that returns a T. In this case you would call it like this: new SomeDelegate<string>(course.Name)

delegate T SomeDelegate<T>(Func<T> param);

Above is a slightly more complex delegate, which means you are passing in a function that evaluates to T when it is done. Lambdas are pretty good at handling that. In this case you would call it like this: new SomeDelegate<string>(course => course.Name)

You can read more about lambdas, expressions, etc. here: https://msdn.microsoft.com/en-us/library/bb397687.aspx

Upvotes: 1

D Stanley
D Stanley

Reputation: 152556

Your delegate definition requires that the type of the input parameter and the output be the same. In your case, you are trying to pass in an object with a Name property and return a string, which violates the signature of your delegate.

Change your delegate to

delegate TOut SomeDelegate<TIn, TOut>(Tin param);

or use the built-in Func delegates.

Upvotes: 4

Related Questions