Skip to content

Instantly share code, notes, and snippets.

@wi7a1ian
Created September 7, 2022 10:34
Show Gist options
  • Save wi7a1ian/b78cf5c8b446c9d696041acac6c4e324 to your computer and use it in GitHub Desktop.
Save wi7a1ian/b78cf5c8b446c9d696041acac6c4e324 to your computer and use it in GitHub Desktop.
Builder base class in #csharp
using System;
using System.Threading.Tasks;
namespace FooBar
{
public interface IBuilder { }
public interface IBuilder<TBuildResult, TBuilder> : IBuilder
where TBuildResult : class, new()
where TBuilder : class, IBuilder
{
TBuildResult Build();
TBuilder With(Action<TBuildResult> setAction);
TBuilder With<TRequestBuilder>(Action<TBuildResult, TRequestBuilder> setAction) where TRequestBuilder : class, IBuilder, new();
}
public class BuilderBase<TBuildResult, TBuilder> : IBuilder<TBuildResult, TBuilder>
where TBuildResult : class, new()
where TBuilder : class, IBuilder
{
protected TBuildResult obj = default(TBuildResult);
public virtual TBuildResult Build()
{
var inst = obj.GetType().GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
return inst?.Invoke(obj, null) as TBuildResult;
}
public TBuilder With(Action<TBuildResult> setAction)
{
setAction?.Invoke(obj);
return this as TBuilder;
}
public async Task<TBuilder> With(Func<TBuildResult, Task> setAction)
{
await setAction?.Invoke(obj);
return this as TBuilder;
}
public TBuilder With<TRequestBuilder>(Action<TBuildResult, TRequestBuilder> setAction)
where TRequestBuilder : class, IBuilder, new()
{
setAction?.Invoke(obj, new TRequestBuilder());
return this as TBuilder;
}
public async Task<TBuilder> With<TRequestBuilder>(Func<TBuildResult, TRequestBuilder, Task> setAction)
where TRequestBuilder : class, IBuilder, new()
{
await setAction?.Invoke(obj, new TRequestBuilder());
return this as TBuilder;
}
public static implicit operator TBuildResult(BuilderBase<TBuildResult, TBuilder> builder)
=> builder.Build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment