locked
Conversion of Func<Type1,returnType> to Func<Type2,returnType> RRS feed

  • Question

  • I have a method M taking Func<Interface,bool>factoryMethod  as input parameter and I have another method M' to be implemented in M which takes Func<ChildClass,bool>SomeMethod as input.

    How do I use factoryMethod to pass it as parameter  SomeMethod ? (Here ChildClass inherits from Interface)

    Wednesday, June 19, 2013 7:00 AM

Answers

  • I would do it like this:

            private static void Test1(Func<TestImplementation,bool> t)
            {
                Func<ITestInterface, bool> t1 = s => t((TestImplementation)s);
                Test2(t1);
            }
    
            private static void Test2(Func<ITestInterface,bool> t)
            {
    
            }


    Best regards, Chernobrivets


    • Edited by Chernobrivec Wednesday, June 19, 2013 8:57 AM corrected mistakes
    • Marked as answer by _Kryptx Wednesday, June 19, 2013 9:03 AM
    Wednesday, June 19, 2013 8:57 AM

All replies

  • Hi,

    I've tried this code and it works:

    class Program
        {
            static void Main(string[] args)
            {
                    Func<ITestInterface, bool> t = s => String.IsNullOrEmpty(s.Title);
                    Test1(t);
            }
    
            private static void Test1(Func<ITestInterface,bool> t)
            {
                Test2(t);
            }
    
            private static void Test2(Func<TestImplementation,bool> t)
            {
    
            }
        }
    
        interface ITestInterface
        {
            string Title { get; set; }
        }
    
        public class TestImplementation : ITestInterface
        {
            public string Title { get; set; }
        }

    Or did you mean something else?

    Best regards, Chernobrivets

    Wednesday, June 19, 2013 7:18 AM
  • Sorry,My mistake.

    I actually meant the other way round. I mean  a Func<ChildClass,bool>SomeMethod is passed as parameter to a function which  must implement a method with Func<Interface,bool>SomeOtherMethod as parameter.

    Now How do I solve it ?

    Wednesday, June 19, 2013 8:02 AM
  • Thanks for your help.

    I have found the answer.

    Wednesday, June 19, 2013 8:53 AM
  • I would do it like this:

            private static void Test1(Func<TestImplementation,bool> t)
            {
                Func<ITestInterface, bool> t1 = s => t((TestImplementation)s);
                Test2(t1);
            }
    
            private static void Test2(Func<ITestInterface,bool> t)
            {
    
            }


    Best regards, Chernobrivets


    • Edited by Chernobrivec Wednesday, June 19, 2013 8:57 AM corrected mistakes
    • Marked as answer by _Kryptx Wednesday, June 19, 2013 9:03 AM
    Wednesday, June 19, 2013 8:57 AM