c# - How do I make the return OBJECT of a method generic? -


i need somthing below code, new t() not work. says "cannot create instance of variable type t because not have new() constraint."

public static t maptobasedropdown2<t>(this genericdropdowndata dd) t : basedropdown {     return new t() //fails     {         id = dd.id,         description = dd.description     }; } 

basedropdown base class 3 childs entities mapped entityframework (code first), may better keep simple possible.

now not abstract due implementations tried, if possible be.

public class basedropdown {     public int id { get; set; }     public string description { get; set; } } 

calling new t() assumes every type has parameterless-constructor, doesn´t seem case here. if base-class basedropdown has such constructor isn´t guranteed subclasses, in particular abstract ones:

class basedropdown {     public basedropdown() { /* see parameterless-constructor exists */ } } abstract class myclass : basedropdown {     public myclass() { ... } } 

now use new-constraint exclude abstract classes:

public static t maptobasedropdown2<t>(this genericdropdowndata dd) t : basedropdown, new() 

that constraint onlx allow classes inherit basedropdown and instantiable using parameterless constructor.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -