Generics and base Inheritance issue

  • Thread starter Thread starter Craig Muckleston (MCPD, MCTS)
  • Start date Start date
C

Craig Muckleston (MCPD, MCTS)

Guest
I am trying to create a generic repository and return a list of entities. My own entity inherits from a base entity which the repository requires as it's generic T. When I return my newly created list, I can see the return value has entities, but each entity returned is null

My code looks like this:

using PushyHedge.Standard.ExtensionMethods;
using System;
using System.Collections.Generic;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
var at = new MyRepository<MyEntity>();
List<MyEntity> myResults = at.GetStuff();
myResults.ForEach(x =>
{
Console.WriteLine(x.ToString());
});
Console.ReadLine();
}
}
public class MyBaseEntity
{
public int Id { get; set; }
}
public class MyEntity : MyBaseEntity
{
}
public class MyRepository<T> where T : MyBaseEntity
{
public List<T> GetStuff()
{
List<T> results = new List<T>();
for (int i = 1; i < 11; i++)
results.Add(new MyBaseEntity() { Id = i } as T );
return results; //each entity here is null
}
}
}

Continue reading...
 
Back
Top