I am working on a ASP.NET MVC project, with C#, and EF code first.
I am required to add dynamic properties to entities. For example -
I have a car as a base object. I can add custom properties for it like engine power, length, color etc etc.
Properties can be boolean, int, string or select options (ie, i have to create checkbox, input or select html elements when a user inputs values for those properties).
Properties must have custom validation rules (i.e., required, number only, range only etc).
Can you guys give me any clues or direction how to accomplish this?
Thank you
If you truly have dynamic properties you won't be able to do this (directly) with EF6 since EF6 assumes a relation database. and a relational database needs to know which columns to expect.
Now you got 2 options.
Option1:
use a non-relational database with EF 7. you can look here https://msdn.microsoft.com/en-us/magazine/dn890367.aspx for some more details about EF7 but basically in a non relation database you can store any json blob - so also your dynamic properties
Option 2: Use a key value pair within your object. and store those properties
class KeyValuePair {
int Id {get; set;}
string name {get; set;}
string stringValue {get; set;}
}
class BaseObject {
int Id {get; set;}
list<KeyValuePair> dynamicProperties {get; set;}
}
Now your car can just inherit from this baseobject. You still need to do the work to create your KeyValuePair objects. (And if you want to store strings, ints etc you can make Different KeyValuePair types, one for each storage type)
Be carefull with performance though if you use dynamic properties like this.
Update:
If you want to validate a dynamic object like this you want to implement IValidatableObject
so you get
class Car: BaseObject, IValidatableObject {
public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
/* code to validate your properties here, for example you need at least 1 engine, 4 wheels etc */
yield return ValidationResult.Success;
}
}
You can create and use tables in DB dynamically, although it's not so simply.
First, you'll need to store metadata about your tables — what are their names, what are properties they have, what are the types of those properties, and so on.
Second, you'll need to generate entities to access these tables, and also, EntityTypeConfiguration classes, like here:
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
public class FooTypeConfiguration : EntityTypeConfiguration<Foo>
{
public FooTypeConfiguration()
{
ToTable("Foos");
HasKey(t => t.Id);
Property(t => t.Name).HasMaxLength(200)
.IsRequired();
}
}
You can generate DLL dynamically without intermediate C# code with help of System.Reflection.Emit. Or you can generate C# code and use System.CodeDom.Compiler to compile it (this way is simpler). You can also try Roslyn compiler (but I don't have enough experience to advise it).
Third, you'll need to load compiled DLL and create DbContext using modelBuilder.Configurations.AddFromAssembly(...).
You can find required type in assembly and use it to access data:
string typeName = ...;
var type = dynamicLoadedAssembly.GetType(typeName);
var set = dbContext.Set(type); // non-generic DB Set
You can use System.Reflection or dynamic typing to work with these objects.
Finally, if you'll generate C# code, you can generate properties and implementation of some interface to access these properties by names:
public interface IAccessorByName : IReadOnlyDictionary<string, object>
{
object this[string name] { get; set; }
}
public Foo : IAccessorByName
{
private static readonly IDictionary<string, Func<Foo, object>> getters = new Dictionary<string, Func<Foo, object>>
{
{ "Id", (foo) => foo.Id },
{ "Name", (foo) => foo.Name },
};
private static readonly IDictionary<string, Action<Foo, object>> setters = new Dictionary<string, Action<Foo, object>>
{
{ "Id", (foo, value) => { foo.Id = (int)value; } },
{ "Name", (foo, value) => { foo.Name = (string)value; } },
};
public int Id { get; set; }
public string Name { get; set; }
public object this[string name]
{
get { return getters[name](this); }
set { setters[name](this, value); }
}
}
With similar interface you can create, read, update, and delete objects dynamically:
string typeName = "Foo";
var fooType = dynamicLoadedAssembly.GetType(typeName);
var foo = (IAccessorByName)Activator.CreateInstance(fooType);
foo["Id"] = 1;
foo["Name"] = "Jon Skeet";
var fooSet = dbContext.Set(fooType);
fooSet.Add(foo);
dbContext.SaveChanges();
Related
Let's say I have n objects:
class RedSubscriber {
String msisdn {get; set;}
String imsi {get; set;}
...other unique properties specific for RedSubscriber
}
class BlueSubscriber {
String msisdn {get; set;}
String imei {get; set;}
...other unique properties specific for BlueSubscriber
}
class YellowSubscriber {
String msisdn {get; set;}
String iccid {get; set;}
...other unique properties specific for YellowSubscriber
}
And so on, for n objects.
Let's say I want to get the "String msisdn" value of any object, regardless of what color it is. I currently do it using Reflection:
public void getSubscriberMsisdn(Object subscriber){
Type myType = subscriber.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo propertyInfo in props)
{
if (propertyInfo == null)
{
continue;
}
var propertyValue = propertyInfo.GetValue(subscriber);
if (propertyValue == null)
{
continue;
}
if(propertyInfo.Name.Equals("msisdn")){
string msisdnValue = propertyValue.ToString();
Debug.WriteLine("The msisdn is: " + msisdnValue);
}
}
}
As you can see the code "works", but is absolutely wasteful to call it everytime I need to retrieve some values. Is there a way to access a property (that always maintains the same name and type) that is placed inside different objects, without using the aforementioned reflection method? Any tip will be appreciated.
Yes. Create an interface:
public interface ISubscriber
{
public string msisdn {get; set;};
}
Change your classes to implement the interface, e.g.:
public class RedSubscriber : ISubscriber
{
string msisdn {get; set;}
string imsi {get; set;}
...
}
Create a getSubscriberMsisdn() method that takes an ISubscriber:
public void getSubscriberMsisdn(ISubscriber subscriber)
{
Debug.WriteLine("The msisdn is: " + subscriber.msisdn);
}
Don't use reflection for polymorphism. Interfaces is a language feature that directly supports polymorphism and supports strong typing at compile time.
In situations like this there are two standard options:
Interface
Inheritance
Where to use which not always clear and very often both approaches work.
I think inheritance could work here because your models have a very strong "IS-A" relationship. It could look something like this:
abstract record Subscriber
{
public required string Msisdn { get; init; }
}
record RedSubscriber : Subscriber
{
public required string Imsi { get; init; }
}
record BlueSubscriber : Subscriber
{
public required string Imei { get; init; }
}
And then
void F(Subscriber s)
{
Console.WriteLine(s.Msisdn);
}
Notes:
I capitalised the names of properties, it's the C# way.
I took advantage of 'required'+'init' properties to ensure they are never null
I used records instead of classes because it seems like a good fit: simple classes with value - rather than reference - equality.
You don't need to use records - just replace 'record' with 'class' in the code above.
BTW. You could remove some of the boiler plate code by using positional records with more concise syntax:
abstract record Subscriber(string Msisdn);
sealed record RedSubscriber(
string Msisdn,
string Imsi)
: Subscriber(Msisdn: Msisdn);
sealed record BlueSubscriber(
string Msisdn,
string Imei)
: Subscriber(Msisdn: Msisdn);
I red this article: The entity cannot be constructed in a LINQ to Entities query , but guess it's not fully related to my issue.
I have this code:
public class Class1
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
}
[Table("Class2")]
public class Class2
{
[Key]
[Column("Prop1")]
public string Prop1 { get; set; }
[Column("Prop2")]
public string Prop2 { get; set; }
[Column("Prop3")]
public string Prop3 { get; set; }
}
and method edit where I want to use these ones:
using (var data = new Context())
{
var config = data.Class2.FirstOrDefault(c => c.Prop1.Contains(some_string));
if (config != null)
{
config.Prop1 = class1_instance.Prop1;
config.Prop2 = class1_instance.Prop2;
config.Prop3 = class1_instance.Prop3;
}
data.Entry(config).State = EntityState.Modified;
data.SaveChanges();
}
So what I want to get is simplify editing, instead of assigning each property one by one I want to write something like config = class1_instance;
So I've inherited Class1 from Class2, but getting
System.NotSupportedException (the entity or complex type "Class1" cannot be constructed in a Linq to Entities query).
How can I handle it?
Don't inherit the DTO class from the entity class because EF6 will treat the DTO as an entity participating in some of the supported database inheritance strategies.
Instead, use the SetValues(object) of the DbPropertyValues returned by the CurrentValues property of the DbEntityEntry:
Sets the values of this dictionary by reading values out of the given object. The given object can be of any type. Any property on the object with a name that matches a property name in the dictionary and can be read will be read. Other properties will be ignored. This allows, for example, copying of properties from simple Data Transfer Objects (DTOs).
e.g.
Class1 source = ...;
var target = data.Class2.FirstOrDefault(...);
if (target != null)
{
data.Entry(target).CurrentValues.SetValues(source);
data.SaveChanges();
}
Note that the target entity is already attached (tracked) by the db context, so there is no need to set the entry state to Modified.
Now Class1 and Class2 have equal properties. Is that intended, or is this by accident, and might it be that future versions of Class2 have properties that are not in Class1?
In entity framework, the DbSet<...> represent the tables of your database. the class in the DbSet represents one row in the table. The columns of your table are the non-virtual properties of the class; the virtual properties represent the relations between the tables (one-to-many, many-to-many, ...)
Class2 represents a database table. If Class1 is supposed to be equal to Class2, then what is the reason for Class1. If this equality is only now, and in future versions they might be different, you'll have to copy the properties one-by-one.
void UpdateValue(string someString, Class1 value)
{
using (var dbContext = new DbContext())
{
Class2 fetchedData = dbContext.Class2.Where(...).FirstOrDefault();
if (fetchedData != null)
{ // data exists. Update the properties
fetchedData.Prop1 = value.Prop1,
fetchedData.Prop2 = value.Prop2,
fetchedData.Prop3 = value.Prop3,
// future version of Class2 may have properties that are not updated
// no need to set state to modified. Entity Framework will detect the changes
dbContext.SaveChanges();
}
}
}
If you are absolutely certain that every Class2 is a special type of Class1, now and in far future, you might consider to derive Class2 from Class1:
class Class2 : Class1
{
public int Id {get; set;}
... // properties that are in Class2, but not in Class1
}
This means that every non-virtual property of Class1 is represented by a column in the tables with Classes2.
Derivation won't help you, even if you derive, you'll have to copy the properties one by one. If you'll have to do this several times consider to create a function that copies the proper values for you.
I have 3 objects Vehicle, Car and MotorCycle. Vehicle is the abstract base class for Car and MotorCycle.
public abstract class Vehicle
{
public String Color {get;set};
public Int Price {get;set};
public DateTime ReleaseDate {get;set};
}
public class Car : Vehicle
{
public Int EnginePower {get;set};
public Int TrunkSpace {get;set};
public bool GearBoxType {get;set};
public Int Seats {get;set};
}
public class MotorCycle : Vehicle
{
public Int EnginePower {get;set};
public String Type{get;set};
}
I want to stock all the Vehicles (Cars, motorcycles...) in the same collection of documents in RavenDb. So I am using this convention and it works :
documentStore.Conventions.FindTypeTagName =
type => type.IsSubclassOf(typeof(Vehicle)) ?
DocumentConvention.DefaultTypeTagName(typeof(Vehicle)) :
DocumentConvention.DefaultTypeTagName(type);
Now I want to do indexs for my requests for all vehicles. But i want to request on Vehicle properties and on implementations (Car, MotorCycle) properties.
Examples of requests i would :
All vehicles with Color="red", EnginePower>100
All vehicles with Color="red", EnginePower>100, Seats=5
All vehicles with Type="Scooter"
etc....
And the result in only one collection of Vehicule type, order by RealeaseDate.
How to do a query like that in C# and linq ?
RavenDB will save the entities as their deriving types and build any automatic index based on those types.
What you need to do is create a new index that indexes the properties in the base class across all the different types and then select from that index.
public class VehicleIndex : AbstractMultiMapIndexCreationTask
{
public VehicleIndex()
{
this.AddMap<Car>(vehicle => from v in vehicle select new { v.Price , v.Color , v.ReleaseDate });
this.AddMap<Motorcycle>(vehicle => from v in vehicle select new { v.Price , v.Color , v.ReleaseDate });
}
}
I have written a more in depth blog post about this using interfaces but exactly the same technique works for abstract base classes. See blog post here
It is actually a very powerful technique and allows you to fully leverage the schema-less nature of Raven.
I came across this thread and would like to correct the comments / answer posted here so far.
It is possible to create an index of all inheritances.
Generally speaking, it is best to save all your inheritances in seperate collections. So, in other words, to not save Car as a Vehicle in Raven, but as a Car.
You can then use a MultiMapIndex to query on similarities between the different inheritances, but also retain the option to create a seperate index for a specific inheritance, should the need arise.
To get the result you need, simply save the results as a new type wherein you include all properties you want to index (or even create new ones based on input of the child classes)
public class VehicleIndex : AbstractMultiMapIndexCreationTask
{
public class Mapping
{
public string Price { get; set; }
public string Color { get; set; }
public string ReleaseDate { get; set; }
public int? EnginePower { get; set;}
}
public VehicleIndex()
{
this.AddMap<Car>(vehicle => from v in vehicle select new Mapping()
{
Price = v.Price,
Color = v.Color,
ReleaseDate = v.ReleaseDate,
EnginePower = v.EnginePower
});
this.AddMap<Motorcycle>(vehicle => from v in vehicle select new Mapping()
{
Price = v.Price,
Color = v.Color,
ReleaseDate = v.ReleaseDate,
EnginePower = v.EnginePower
});
}
}
I saved EnginePower as an int? so you can add childs to this class that do not have EnginePower and store them as null. This allows you to filter on motorcycles and cars by doing where(a => a.EnginePower.HasValue && (a.EnginePower > 50 || a.EnginePower < 100))
EDIT: I have since added a custom overload that simply scans the whole solution for classes deriving from T, and adding them to the index as a new map. This means that if a new child gets added, you don't have to manually add them to index definition but simply recompile your indexes and you're good to go.
public void AddMapForPolymorphic<TBase>(Expression<Func<IEnumerable<TBase>, IEnumerable>> expr)
{
AddMap(expr);
var children = Modules.Modules.Instance.GetModules()
.SelectMany(a => AssemblyHelper.GetClassesWithBaseType<TBase>(a.GetType().Assembly)
);
var addMapGeneric = GetType()
.GetMethod("AddMap", BindingFlags.Instance | BindingFlags.NonPublic);
foreach (var child in children)
{
if (!child.HasAttribute<IgnorePolymorpAttribute>())
{
var genericEnumerable = typeof(IEnumerable<>)
.MakeGenericType(child);
var delegateType = typeof(Func<,>)
.MakeGenericType(genericEnumerable, typeof(IEnumerable));
var lambdaExpression = Expression.Lambda(delegateType, expr.Body, Expression
.Parameter(genericEnumerable, expr.Parameters[0].Name));
addMapGeneric
.MakeGenericMethod(child).Invoke(this, new[] { lambdaExpression });
}
}
}
I have two lists of different objects, one from a third party API and one from my database - and I'm trying to link the two as a relationship. Ideally with a similar effect of how DBML's create relationships for tables with foreign keys (Customer.Orders).
From third party:
class ApiObject {
public string ID { get; set; }
public string Title { get; set; }
public DateTime CreatedDate { get; set; }
... 30 other properties ...
}
From my database:
class DbmlObject {
public int ID { get; set; }
public string ApiID { get; set; }
public string OtherString { get; set; }
}
They are related through ApiObject.ID == DbmlObject.ApiID
I do not want to merge these, nor join them into some anonymous object (and explicitly list 30+ properties) - but rather to make the DbmlObject a linked property of ApiObject. i.e.: addressable as:
apiObject.DbmlObjects.First().OtherString or ideally apiObject.DbmlObject.OtherString since it is a 1 to 1 relationship.
In controller:
List<ApiObject> apiObjects = _thirdParty.GetObjects();
DbmlDataContext model = new DbmlDataContext();
List<DbmlObject> dbmlObjects = model.GetAllDbmlObjects();
// relate them here
foreach (var apiObject in apiObjects)
Console.Write(apiObject.DbmlObject.OtherString)
// NOTE: ideally this foreach loop should not make a DBML query on each iteration, just the single GetAllDbmlObjects query above.
It sounds like a join:
var combined = from api in apiObjects
join dbml in dbmlObjects on api.ID equals dbml.ApiID
select new { api, dbml }
In order to get DbmlObject "in" the ApiObject, you will need to either inherit ApiObject and construct a new one of that class, which includes the Dbml property, or create a entirely new class to return. If you need static typing this is the best you can do - of course you could (mis)use dynamic to get what you want.
In this case, you are mentioning (in comments) that the ApiObject class is from a third party library that you can't change - in this case I would probably choose to create a new type which takes an instance of both objects in the constructor and exposes the properties you need - a decorator. Yes, it looks like a lot of code, but it is not complex, good tools will autogenerate it for you - and you get the class that you need for your code to be succinct.
In case you want to go further with returning an IEnumerable<dynamic>, you could build a "combining dynamic" object based on DynamicObject that then responds to all the properties of ApiObject and DbmlObject - or just adds DbmlObject as a property. I am not saying this is the right way to go, it depends on what you need it for - remember you are losing type safety. Here is a simple example:
void Main()
{
dynamic dyn = new CombiningDynamic(new Foo { X = 3 }, new Bar { Y = 42 });
Console.WriteLine(dyn.X);
Console.WriteLine(dyn.Y);
}
public class Foo
{
public int X {get;set;}
}
public class Bar
{
public int Y { get;set;}
}
public class CombiningDynamic : DynamicObject
{
private object [] innerObjects;
public CombiningDynamic(params object [] innerObjects)
{
this.innerObjects = innerObjects;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
foreach(var instance in innerObjects)
{
Type t = instance.GetType();
PropertyInfo prop = t.GetProperty(binder.Name);
if (prop != null && prop.CanRead)
{
result = prop.GetValue(instance, null);
return true;
}
}
result = null;
return false;
}
}
Remember, this is example code. If you really go this way, you would want to perhaps override some more of the methods (TrySetMember, ...), and you most definetely would want to cache the reflection results so you don't need to walk the types each time - reflection is (comparatively) slow.
I have a set of custom data types that can be used to manipulate basic blocks of data. For example:
MyTypeA Foo = new MyTypeA();
Foo.ParseString(InputString);
if (Foo.Value > 4) return;
Some of these types define read-only properties that describe aspects of the types (for example a name, bit size, etc.).
In my custom framework I want to be able to provide these types to the user for use in their applications but I also want to give the user a list of the available types which they could easily bind to a combobox. My current approach:
public static class DataTypes
{
static ReadOnlyCollection<MyDataType> AvailableTypes;
static DataTypes()
{
List<MyDataType> Types = new List<MyDataType>();
Types.Add(new MyTypeA());
Types.Add(new MyTypeB());
AvailableTypes = new ReadOnlyCollection<MyDataType>(Types);
}
}
What concerns me about this is that the user might obtain a type from the AvailableTypes list (by selecting a combobox item for example) and then use that reference directly rather than creating a clone of the type and using their own reference.
How can I make the list of available types read only so that it doesn't allow any writing or changes to the type instances, forcing the user to create their own clone?
Alternatively is there a better way of providing a list of available types?
Thanks, Andy
Make your custom Type class immutable, same as System.Type and you dont have to worry. A end user can fetch all the data it wants but he can not modify the object in any way.
EDIT: Example of immutable class
Take the following class for instance:
public class ImmutablePerson
{
private readonly string name; //readonly ensures the field can only be set in the object's constructor(s).
private readonly int age;
public ImmutablePerson(string name, int age)
{
this.name = name;
this.age = age;
}
public int Age { get { return this.age; } } //no setter
public string Name { get { return this.name; } }
public ImmutablePerson GrowUp(int years)
{
return new ImmutablePerson(this.name, this.age + years); //does not modify object state, it returns a new object with the new state.
}
}
ImmutablePerson is an immutable class. Once created there is no way a consumer can modify it in any way. Notice that the GrowUp(int years) method does not modify the state of the object at all, it just returns a new instance of ImmutablePerson with the new values.
I hope this helps you understand immutable objects a little better and how they can help you in your particular case.
To get around the problems you've mentioned, you could create a wrapper around your instances, and have the wrapper provide the functionality you require.
For example:
public class TypeDescriptor
{
private MyDataType _dataType;
public TypeDescriptor(MyDataType dataType)
{
_dataType = dataType;
}
public override string ToString()
{
return _dataType.ToString();
}
}
You class would then look something like:
public static class DataTypes
{
public static ReadOnlyCollection<TypeDescriptor> AvailableTypes;
static DataTypes()
{
List<TypeDescriptor> Types = new List<TypeDescriptor>();
Types.Add(new TypeDescriptor(new MyTypeA()));
Types.Add(new TypeDescriptor(new MyTypeB()));
AvailableTypes = new ReadOnlyCollection<TypeDescriptor>(Types);
}
}
Binding to the list and relying on the ToString() will now result in your data types ToString being called.
Create a list of types rather than a list of instances. e.g.
List<Type> Types = new List<Type>();
Types.Add(typeof(MyTypeA));
Types.Add(typeof(MyTypeB()));
etc.
To answer the comment on binding to a drop down list:
MyDropDown.Datasource = Type.Select(t => t.Name);
MyDropDown.DataBind();
This will not use the custom property of your classes but it will give you the simple calss name without all the other guff e.g. MyTypeA
A collection cannot "inject" type modifiers into its members. The collection you have declared is readonly. If you want MyDataType to be readonly you must declare that way.
Somthing like :
EDIT extended class to have a parse method
public class MyDataType
{
private MyDataType()
{
...
}
internal static MyDataType Parse(string someString)
{
MyDataType newOne = new MyDataType();
newOne.Value = ... //int.Parse(someString); ?
}
public int Value { get; private set; }
}
If the collection stays generic there is no readonly constraint.
You would use it like this, following your example.
MyTypeA foo = MyTypeA.Parse(inputString);
if (foo.Value > 4) return;
You probably shouldn't store instances of your types in the list. Instead you can store types. These can be used to create instances:
public static class DataTypes
{
static ReadOnlyCollection<Type> AvailableTypes;
static DataTypes()
{
List<Type> Types = new List<Type>();
Types.Add(typeof(MyTypeA));
Types.Add(typeof(MyTypeB));
AvailableTypes = new ReadOnlyCollection<MyDataType>(Type);
}
}
You can use Activator.CreateInstance to create a concrete instance:
Object myType = Activator.CreateInstance(AvailableTypes[0]);
Unless your types share a common base type you cannot downcast the result and an Object isn't that useful.
Also the use of the term type in your code makes my example a bit confusing as I suggest you store the types of something called type.
You could consider creating and attribute that you then can apply to MyTypeA, MyTypeB etc. Then you can build the AvailableTypes using reflection and the list will always be up to date with your code. E.g. if you add MyTypeC and use the attribute it will automatically be added to the list.
You can also add a display string property to the attribute and use that for display in the combo box. If you want to do that you should store a small object combining the type and the display string in AvailableTypes.
Here is an example. Using generic words like type and data can be confusing so to pick a random name I just use foo. Obviously you should use a more descriptive name.
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
sealed class FooAttribute : Attribute {
public FooAttribute(String displayName) {
DisplayName = displayName;
}
public String DisplayName { get; private set; }
}
You can decorate you classes using this attribute:
[Foo("Type A")]
class MyTypeA { ... }
[Foo("Type B")]
class MyTypeB { ... }
For the combobox you want a list of factory objects with a nice ToString implementation (this class can be improved by adding some error handling which I have left out to save space):
class FooFactory {
readonly Type type;
public FooFactory(Type type) {
this.type = type;
DisplayName = ((FooAttribute) Attribute.GetCustomAttribute(
type,
typeof(FooAttribute))
).DisplayName;
}
public String DisplayName { get; private set; }
public Object CreateFoo() {
return Activator.CreateInstance(this.type);
}
public override String ToString() {
return DisplayName;
}
}
Returning Object from CreateFoo isn't very useful but that is a separate issue.
You can build this list at run-time:
var factories = Assembly
.GetExecutingAssembly()
.GetTypes()
.Where(t => Attribute.IsDefined(t, typeof(FooAttribute)))
.Select(t => new FooFactory(t));
I'm not exactly sure of what you want but should something like this be ok ?
public static class DataTypes
{
static Dictionary<string,Type> AvailableTypes
= new Dictionary<string,Type>()
{
{ "MyTypeA", MyTypeA },
{ "MyTypeB", MyTypeB },
...
};
}
That is actually return types instead of sample instances of theses types. Thus you would be sure that only new instances would be created by the user of your class.
Then in the calling code :
MyTypeA a = Activator.CreateInstance(DataTypes.AvailableTypes["MyTypeA"]);