Skip to content

Advanced Features ​

Enum Type Support ​

When using an enum type with Select or MultiSelect, items are automatically generated from the enum values. You can use the [Display] attribute to customize the display names:

csharp
using System.ComponentModel.DataAnnotations;

public enum MyEnum
{
    [Display(Name = "First value")]
    First,
    [Display(Name = "Second value")]
    Second,
    [Display(Name = "Third value")]
    Third
}

var value = Prompt.Select<MyEnum>("Select enum value");
Console.WriteLine($"You selected {value}");

For MultiSelect:

csharp
var values = Prompt.MultiSelect<MyEnum>("Select enum values");
Console.WriteLine($"You picked {string.Join(", ", values)}");

Item Order ​

Enum items are listed in the same order whether the metadata comes from the Sharprompt source generator or from the reflection fallback (used when the generator did not run, for example for enums in another assembly):

  1. Members are ordered by their underlying value, not by declaration order. Negative values come first for signed enums. Composite values of [Flags] enums are ordinary members and are sorted with the rest.
  2. Aliases (members that share a value) appear once. The alias whose name sorts first in ordinal order represents the value, and only its [Display] attribute is used.
  3. Members with [Display(Order = ...)] come first, sorted by Order. Members without Order come after all of them, even after Order = int.MaxValue. Members with the same Order, and members without one, keep the value order.
csharp
public enum Priority
{
    Low = 1,
    [Display(Name = "High priority", Order = 0)]
    High = 3,
    Medium = 2,
    Normal = 2 // Alias of Medium. "Medium" sorts first, so it represents the value.
}

// Items: High priority, Low, Medium
var priority = Prompt.Select<Priority>("Select priority");

Display Names and Localization ​

An item's text is [Display(Name = ...)], or the member name when there is no Name. To localize it, set ResourceType as well. Name is then the name of a property on that type, as with any DisplayAttribute. The type must be public, and the property must be a public static string, such as the properties generated by PublicResXFileCodeGenerator:

csharp
public enum Priority
{
    [Display(Name = nameof(Strings.PriorityLow), ResourceType = typeof(Strings))]
    Low,
    [Display(Name = nameof(Strings.PriorityHigh), ResourceType = typeof(Strings))]
    High
}

The property is read each time the items are shown, so the names follow CultureInfo.CurrentUICulture (or the culture your resource class is set to). Prompt.Culture only changes Sharprompt's own messages, not your resources. If the property returns null, the member name is shown.

Notes and Limitations ​

  • Only Name, ResourceType, and Order of [Display] are used. ShortName, Description, GroupName, and Prompt are ignored, and so are other attributes such as [Description] and [EnumMember].
  • For [Flags] enums, each member is a separate item, including composite members. MultiSelect returns the selected members as a collection; it does not combine them into a single flags value.
  • The source generator does not generate metadata for enums that use ResourceType on any member, since their names are resolved through DisplayAttribute.GetName. It also skips enums declared in another assembly, nested in a private, protected, or generic type, or declared file. These enums use the reflection fallback, which follows the same rules and is supported under Native AOT. An invalid resource reference throws when the items are shown, as DisplayAttribute.GetName does.
  • To use different items or names, register the enum with EnumMetadataRegistry.Register at startup. A registration replaces the metadata from either source.

Unicode Support ​

Sharprompt supports multi-byte characters and emoji. For best results, set the output encoding to UTF-8:

csharp
Console.OutputEncoding = Encoding.UTF8;

var name = Prompt.Input<string>("What's your name?");
Console.WriteLine($"Hello, {name}!");

Control Characters ​

Messages, items, answers, default values, and error messages can come from external data. Before measuring and writing any of them, Sharprompt normalizes control characters, so the prompt keeps its layout and the cursor stays in place:

CharactersShown as
Line breaks (\r\n, \n, \r, U+0085, U+2028, U+2029)A new line. A multi-line message or error message is shown on several lines.
Tab (\t)Spaces up to the next multiple of 8 columns, counted from the start of the line.
ANSI SGR sequences (ESC [ ... m with only digits, ; and : as parameters), which set colors and stylesKept as is, taking no width. A style ends at the end of its line: the next line starts with the prompt's own colors, so repeat the sequence on each line that should keep it.
Other escape sequences, such as cursor movement, screen clearing, and OSCRemoved, because they would move the cursor or change the terminal's state.
Other control charactersVisible symbols: ␀ to ␟ for U+0000 to U+001F, ␡ for DEL, and � for U+0080 to U+009F.

Only the display changes: Select and MultiSelect still return the original items, and Input returns the text as entered. Keys that produce control characters are not inserted into the input. Text being edited, such as a default value inserted with Tab, shows ESC as ␛ instead of applying escape sequences, so the cursor moves over every character.

Fluent Interface ​

All prompt types support a fluent interface via the Sharprompt.Fluent namespace:

csharp
using Sharprompt.Fluent;

var city = Prompt.Select<string>(o => o.WithMessage("Select your city")
                                       .WithItems(new[] { "Seattle", "London", "Tokyo" })
                                       .WithDefaultValue("Seattle"));

The fluent API provides With* methods for setting properties and Add* methods for adding to collections (like validators).

Text Selector ​

For Select and MultiSelect, you can provide a custom function to control how items are displayed:

csharp
var user = Prompt.Select("Select user", users, textSelector: u => u.Name);

Pagination ​

Both Select and MultiSelect support pagination via the pageSize parameter:

csharp
var city = Prompt.Select("Select your city",
    new[] { "Seattle", "London", "Tokyo", "New York", "Singapore", "Shanghai" },
    pageSize: 3);

Looping Selection ​

For both Select and MultiSelect, LoopingSelection controls how Up/Down navigation behaves at page boundaries:

  • true (the default): wraps between the first and last items within the current page.
  • false: moves to the previous or next page, still wrapping between the first and last pages.

With a single page, both settings wrap within that page. Left/Right page navigation wraps between the first and last pages regardless of this setting.

For example, use a page size of two to navigate across pages with Up/Down:

csharp
var city = Prompt.Select(new SelectOptions<string>
{
    Message = "Select your city",
    Items = new[] { "Seattle", "London", "Tokyo" },
    PageSize = 2,
    LoopingSelection = false
});

Native AOT & Source Generators ​

Sharprompt is configured with <IsAotCompatible>true</IsAotCompatible> and supports Native AOT compilation on .NET 8 and .NET 10.

How It Works ​

Sharprompt uses Roslyn Incremental Source Generators to generate code at compile time, eliminating runtime reflection:

  1. [PromptBindable] Generator: Inspects classes and records annotated with [PromptBindable] and generates strongly typed model binding code registered via a C# [ModuleInitializer]. When invoking Prompt.Bind<T>(), Sharprompt uses the precompiled binder with zero reflection.
  2. Enum Metadata Generator: Inspects enum declarations in your project and generates metadata (values, [Display] names, and ordering) registered via a [ModuleInitializer].

Project Configuration & Publishing ​

To publish an application with Native AOT, add <PublishAot>true</PublishAot> to your project file:

xml
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <PublishAot>true</PublishAot>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Sharprompt" Version="..." />
  </ItemGroup>

</Project>

Publish your application using the dotnet publish command targeting your runtime:

sh
dotnet publish -c Release -r win-x64

Replace win-x64 with your target runtime identifier (such as linux-x64 or osx-arm64).

Enum Handling & External Assemblies ​

  • Project Enums: Any enum declared within the consuming project is automatically analyzed by the source generator at compile time. Display names and custom ordering specified with [Display] are generated directly into code.
  • External Enums: Enums from external assemblies (such as BCL enums like DayOfWeek or enums from referenced packages) are not analyzed by the source generator. At runtime, Sharprompt falls back to an AOT-safe reflection mechanism. To avoid reflection entirely or customize the display, register the enum manually at startup:
csharp
using Sharprompt;

EnumMetadataRegistry.Register<DayOfWeek>(
    Enum.GetValues<DayOfWeek>(),
    day => day.ToString()
);

Type Conversion & Custom Types ​

Input and List convert typed text with TypeDescriptor converters, always using the invariant culture. Default value hints, the text that Tab inserts, and answers are formatted the same way, so any value a prompt shows can be typed back as input. For example, 1.5 is shown as 1.5 even when the current culture formats it as 1,5.

The following types are supported, including their Nullable<T> forms. Each one is verified in CI by publishing and running a Native AOT application against the Sharprompt package:

CategoryTypes
Textstring, char
Booleanbool
Integersbyte, sbyte, short, ushort, int, uint, long, ulong, Int128
Floating pointHalf, float, double, decimal
Date and timeDateTime, DateTimeOffset, DateOnly, TimeOnly, TimeSpan
OtherGuid, Uri, Version, enums

Enum input accepts member names (case-insensitive) and numeric values. A value without a named member is shown as its number.

Custom Types ​

To use your own type, annotate it with [TypeConverter] and implement conversion from and to string:

csharp
var temperature = Prompt.Input<Temperature>("Target temperature");

[TypeConverter(typeof(TemperatureConverter))]
public readonly record struct Temperature(double Celsius);

public sealed class TemperatureConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
        => sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);

    public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
        => value is string text && text.EndsWith('C')
            ? new Temperature(double.Parse(text[..^1], culture))
            : base.ConvertFrom(context, culture, value);

    public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType)
        => value is Temperature temperature && destinationType == typeof(string)
            ? temperature.Celsius.ToString(culture) + "C"
            : base.ConvertTo(context, culture, value, destinationType);
}

Sharprompt passes CultureInfo.InvariantCulture as culture. Implement ConvertTo as well, so that default values and answers are shown in a format ConvertFrom accepts.

Under Native AOT, the converter that [TypeConverter] names keeps its constructor, and CI verifies custom converters declared in the application and in a trimmable library. Trim analysis cannot prove this lookup safe in general, so Sharprompt suppresses that warning in one place. Check your converter with your own published application as well.

Limitations

  • A type without a TypeConverter cannot be converted, even if it implements IParsable<T>. BigInteger is one such type. Input for these types is rejected with an error message.
  • Conversion always uses the invariant culture. To accept culture-specific input, convert it yourself with a custom converter, or prompt for a string and parse it.

Validation Attributes ​

The binder that [PromptBindable] generates creates the model's validation attributes in code, so it does not use reflection to find them. Some attribute constructors are marked [RequiresUnreferencedCode], though, and they behave differently:

AttributesUnder trimming and Native AOT
[MinLength], [MaxLength], [Length]These only use reflection to read Count from values that are neither strings nor ICollection. For string, array, or ICollection values (or a List prompt of them), the generated binder adds no warning.
[Compare], [Range(Type, string, string)]These do use reflection, so the warning is kept. Prefer [Range(int, int)] or [Range(double, double)] where you can.

The trim analyzer still reports IL2026 on the line where you apply [MinLength], [MaxLength], or [Length], because their constructors are [RequiresUnreferencedCode]. It does so whether or not Sharprompt is used. For a string or collection property, suppress it there:

csharp
#pragma warning disable IL2026 // MinLength only uses reflection for values that are not strings or ICollection.
[MinLength(8)]
#pragma warning restore IL2026
public string Password { get; set; } = "";

Cancellation ​

All prompts, including model binding, support cancellation via CancellationToken. Pass the token to Prompt.Bind:

csharp
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

try
{
    var form = Prompt.Bind<MyFormModel>(cts.Token);
}
catch (OperationCanceledException)
{
    Console.WriteLine("Operation timed out or was canceled.");
}

If the token is already canceled, Prompt.Bind throws before any prompt is shown. Prompts wait for keys through IConsoleDriver.ReadKey(CancellationToken), which custom console drivers can override when their input source supports cancellation natively. See Canceling from code for details.

Released under the MIT License.