This source generator simplifies the implementation of the Null Object design pattern in C#. It automatically generates a default, "do nothing" implementation of an interface, helping you avoid null reference exceptions and redundant null checks in your code.
- Automatically generates a Null Object implementation for interfaces.
- Reduces the need for null checks, promoting cleaner, safer code.
- Simple and easy-to-use with a single attribute.
To generate a Null Object for an interface, apply the [NullObject] attribute to the interface.
Example:
[NullObject]
public interface ILog
{
public int Id { get; }
public string Login(string username, string password);
public void Info(string message);
public void Warn(string message);
}The generator will automatically create a class that implements the ILog interface with default "do nothing" behavior.
Generated code:
// <auto-generated/>
using DesignPatternCodeGenerator.Attributes.NullObject;
namespace Samples.NullObject
{
public class LogNullObject : ILog
{
public int Id { get; }
public void Info(string message) { }
public void Warn(string message) { }
public string Login(string username, string password)
{
return default(string);
}
}
}You can now safely use the generated LogNullObject class as a default implementation when an instance of ILog is expected, without the need for null checks.
Generated code:
ILog logger = new LogNullObject();
logger.Info("This will do nothing safely.");To use this source generator in your project, add the NuGet package to your project:
dotnet add package Patternify.NullObjectContributions are welcome! If you encounter any issues or have ideas for improvements, feel free to open an issue or submit a pull request.
This project is licensed under the MIT License.