C# incremental generator to create a method that returns the query string of the object.
1. Install the NuGet package
PM> Install-Package QueryStringGenerator
Class must be decorated with QueryString
attribute, which is declared in QueryStringGenerator
namespace.
using QueryStringGenerator;
[QueryString]
public class Model
{
public int? Limit { get; set; }
public int? Offset { get; set; }
public string? Sort { get; set; }
}
By default the generated method name is ToQueryString
, which when called returns the query string of the object.
var model = new Model
{
Limit = 10,
Sort = "Price"
};
Console.WriteLine($"Query string: {model.ToQueryString()}");
/*
This code example produces the following results:
Query string: &limit=10&sort=Price
*/
Below is the auto-generated extension method for the class defined in step 2. above.
// <auto-generated />
namespace QueryStringGenerator.App.Models
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("QueryStringGenerator", "1.0.0")]
public static class QueryStringExtensionForModel
{
public static string ToQueryString(this Model _this)
{
if (_this == null)
{
return string.Empty;
}
var sb = new global::System.Text.StringBuilder();
if (_this.Limit != null)
{
sb.Append($"&limit={_this.Limit}");
}
if (_this.Offset != null)
{
sb.Append($"&offset={_this.Offset}");
}
if (_this.Sort != null)
{
sb.Append($"&sort={System.Net.WebUtility.UrlEncode(_this.Sort)}");
}
return sb.ToString();
}
}
}
- Nullable value types, including enums
- Reference types
NOTE: The query string value for enum is the name of the enum starting with a lowercase character.