Is it possible to do the following (If so I can\'t seem to get it working.. forgoing constraints for the moment)...
If the type (because it\'s ommitted) is inferred,
Actually it is possible if you know for sure that the generic T has the exact property, using the where (generic type constraint) for a specified class with where T : MyClass.
For instance, if you have two entities Foo and Boo:
class Foo
{
public Guid Id {get; set;}
public DateTime CreateDate {get; set;}
public int FooProp {get; set;}
}
class Boo
{
public Guid Id {get; set;}
public DateTime CreateDate {get; set;}
public int BooProp {get; set;}
}
With a little refactor we can create a BaseClass that will hold the common properties:
class BaseModel
{
public Guid Id {get; set;}
public DateTime CreateDate {get; set;}
}
And modify Foo and Boo to be:
class Boo : BaseModel
{
public int BooProp {get; set;}
}
class Foo : BaseModel
{
public int FooProp {get; set;}
}
And If you have a generic service with the constraint type of where T : BaseModel the compiler will allow you to get or set the BaseModel's properties.
Lets say that you want that for every entity (Foo or Boo) added to DB you will want to set the CreateDate and Id properties from code (and not from server default value):
public interface IGenericService
{
void Insert(T obj);
}
public class GenericService : IGenericService where T : BaseModel
{
public void Insert(T obj)
{
obj.Id = Guid.NewGuid();
obj.CreateDate = DateTime.UtcNow;
this._repository.Insert(obj);
}
}