Skip to main content

Convert to Function

  • 2 minutes to read

Purpose

This Code Provider is used to convert a method that returns void, into a function that returns a value of the appropriate type. It is useful for instance when you need to confirm that the execution was successful by returning a boolean variable.

Note

Convert to Function is a cascading Code Provider. That means that the Code Provider affects all method calls and method declarations in interfaces, base and descendant classes.

Availability

Available when the caret is located on a statement that returns a value form the void method.

Usage

  1. Specify the value to be returned from the method.

    Note

    The blinking cursor shows the caret’s position at which the Code Provider is available.

    public interface IMessageSender {
        string Message { get; }
        void Send();
    }
    public class GreetingsSender: IMessageSender {
        public string Message { get { return "Hello!"; } }
        public void Send() {
            Console.WriteLine(Message);
            return true;
        }
    }
    
  2. Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
  3. Select Convert to Function from the menu.

After execution, the Code Provider changes the method’s return type to the of the value returned from it.

public interface IMessageSender {
    string Message { get; }
    bool Send();
}
public class GreetingsSender: IMessageSender {
    public string Message { get { return "Hello!"; } }
    public bool Send() {
        Console.WriteLine(Message);
        return true;
    }
}

Note

This Code Provider is the opposite of Convert to Procedure