Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert my class to dynamic type <T> by using generics

Tags:

c#

generics

I have a function as below.

private IList<ContactList> getEmptyRow()
{
    var _ContactList = new List<ContactList>();
    _ContactList.Add(new ContactList()
    {
        Email = string.Empty,
        Name = string.Empty
    });

    return _ContactList;
}

I would like to change my class ContactList to

private IList<T> getEmptyRow() {  ..... T.Add(new T()....

Is this possible ? and how ?
Every suggestion will be appreciated.

like image 392
Frank Myat Thu Avatar asked Dec 27 '22 16:12

Frank Myat Thu


1 Answers

Something like this perhaps?

public interface IPerson
{ 
    string Email {get;set;}
    string Name {get;set;}
}

public class SomeClass
{
    private IList<T> getEmptyRow<T>() where T : IPerson, new()
    {
        var t = new List<T>();
        t.Add(new T()
        {
            Email = string.Empty,
            Name = string.Empty
        });

        return t;
    }
}

You need an interface or base class so you can set the public properties Email and Name and you need the new() constraint so you can use the default constructor.

like image 170
BrokenGlass Avatar answered Feb 13 '23 04:02

BrokenGlass