I have a class of several fields:
class Entity{
public int field1 {get; set;}
public int field2 {get; set;}
public int field3 {get; set;}
}
However, I want to be able to reuse this class with the other types: string or bool maybe. But the compiler does not like if I replace public int field1 {get; set;} with public T field1 {get; set;} What is the best way to achieve this goal?
You'll need a generic parameter on your type, like this:
class Entity<T> {
public T field1 {get; set;}
public T field2 {get; set;}
public T field3 {get; set;}
}
You can then re-use this like so:
class EntityOfInt : Entity<int> {
///field1 is an int
///field2 is an int
///field3 is an int
}
In .NET 4 and above you can use dynamic
class Entity {
public dynamic field1 {get; set;}
public dynamic field2 {get; set;}
public dynamic field3 {get; set;}
}
possible overide
class Foo : Entity {
public new string field1 {get; set;}
public new int field2 {get; set;}
//field3 is still dynamic
}
This way you can still do boxing and unboxing for both types, and have your fields exposed. If not overrwriten, they will stay dynamic. So you can have simple class syntax and possibility for multiple unconstrained templates within one class.
class above using generic template
class Entity<T1,T2,T3>
where T3: new()
{
public T1 field1 {get; set;}
public T2 field2 {get; set;}
public T3 field3 {get; set;}
}
as you can see this can quickly get out of hand,
but remember, this is not type safe as method with class Entity<T>
, because dynamic fields will accept all types, and override previously used. And you will have to unbox it every time you want to use it as object.
For more information see MSDN
MSDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With