Skip to content

NdubuisiJr/TypeExtender

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

37 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TypeExtender

A light-weight (actually contains one class) library that extends any unsealed type at runtime.

forthebadge

Actions Status Actions Status nuget Nuget

Built by Ndubuisi Jr Chukuigwe


Usage

Simply install nuget package and you are ready to zoom off!

Creating a new class

var className = "ClassA";
var typeExtender = new TypeExtender(className);
var returnedType = typeExtender.FetchType();
var obj = Activator.CreateInstance(returnedClass);

Extending an existing class

var className = "ClassA";
var baseType = typeof(List<string>);
var typeExtender = new TypeExtender(className, baseType);
var returnedClass = typeExtender.FetchType();
var obj = Activator.CreateInstance(returnedClass);

Adding CustomAttribute to type

 var typeExtender = new TypeExtender("ClassA");
 typeExtender.AddAttribute<CustomAAttribute>(new object[] { "Jon Snow" });

Adding Properties to type

There are several overloads on the AddProperty method. Few of them are shown below:

var typeExtender = new TypeExtender("ClassA");
typeExtender.AddProperty("IsAdded", typeof(bool));
typeExtender.AddProperty("IsEnabled", typeof(bool), true);
typeExtender.AddProperty<double>("Length");
typeExtender.AddProperty<double>("Width", true);

You can add properties with custom attributes

 var attributeType = typeof(CustomAAttribute);
 var attributeParams = new object[] { "Jon Snow" };
 var typeExtender = new TypeExtender("ClassA");
 typeExtender.AddProperty("IsAdded", typeof(bool), attributeType, attributeParams);

Adding Field to Type

The AddField method helps add a field to the type you are creating or extending

  var typeExtender = new TypeExtender("ClassA");
  typeExtender.AddField("IsAdded", typeof(bool)); // first overload
  typeExtender.AddField<bool>("IsEnabled"); // second overload