0

I've been trying for long but can't seem to figure out the solution.

A function that takes a string and returns an object of type IVehicle.

Method Signature

public class Car: IVehicle 
{
    public static IVehicle GetCar(Func<string, IVehicle> lambda)
    {
    //...
    }

Method Call

Car.GetCar("lambo" => new Car("lambo"));

Question:

What changes can I do to my call to be compatible with the method signature?

Targeting .NET Framework 4.5.1

1
  • 1
    Note that x => new Car(x) is shorthand for (string x) => new Car(x), makes it easier to see why you can't substitute "lambo" for x. Commented Jan 22, 2017 at 10:51

2 Answers 2

4

GetCar needs a method which takes a string and returns a type which implements IVehicle.

Therefore, you need to provide a method like below:

Car.GetCar(x => new Car(x));

Here is a longer version, without lambda, to explain what is going on there:

Car.GetCar(CallThisMethod);

// See the signature of this method: it takes a string and returns IVehicle
public static IVehicle CallThisMethod(string someString)
{
    return new Car();
}
Sign up to request clarification or add additional context in comments.

4 Comments

can you please test it with actual string in place, isn't your answer same as my attempt?
Car.GetCar("lambo" => new Car("lambo")); isn't the same?
@iPhoneDeveloper You can't have a string on the left side of the '=>'operator, you're just defining a function, you're defining the parameter's name not the parameter itself. Writing "lambo"=> whatever is like trying to write a function with signature IVehicle GetCar("lambo") instead of IVhehicle GetCar(string x), it makes no sense, you're mixing defining the function with calling it
@iPhoneDeveloper no it is not the same. See my edited answer to achieve the same thing without lambda.
0

As @odingYoshi suggested you need to change it so that the Func takes in a variable and uses that one:

Car.GetCar(x => new Car(x));

If you need to pass in the variable x, you could hardcode it in the Func:

Car.GetCar(x => new Car("lambo"));

However, if you need to do that you probably shouldn't be using a Func at all:

public static IVehicle GetCar(string carName)
{
    IVehicle car =  new Car(carName);

    //Anything extra
}

Another alternative is to pass the string into the method as well:

public static IVehicle GetCar(Func<string, IVehicle> lambda, string carName)
{
    IVehicle car =  lambda(carName);

    //Anything extra
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.