Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic field type in C# entity

Tags:

c#

generics

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?

like image 911
J.Doe Avatar asked Sep 05 '25 16:09

J.Doe


2 Answers

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
}
like image 109
Alex Avatar answered Sep 07 '25 10:09

Alex


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

like image 31
Tomasz Juszczak Avatar answered Sep 07 '25 09:09

Tomasz Juszczak