Creating a new object where his type is passed to a method

BitSmithy 1,751 Reputation points
2020-06-16T15:52:09.233+00:00

Hello,

I am trying such code. I want to create a new object and add it to the list, but the class of the object is passed to the method.

        public List<T> GetDataList<T>(T dataObject)
        {
            var dataList = new List<T>();

            var newDataObject = new T();

            dataList .Add(newDataObject );

                        return dataList;

               }

Line: var newDataObject = new T(); doesnt work.
Is it possible to do my task, and how?

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,231 Reputation points
    2020-06-16T16:35:33.06+00:00

    Hi, Your code must look like this:

      public List<T> GetDataList<T>(T dataObject)
      {
        var dataList = new List<T>();
    
        var newDataObject = (T)Activator.CreateInstance(typeof(T), dataObject);
    
        dataList.Add(newDataObject);
    
        return dataList;
    
      }
    
    0 comments No comments

0 additional answers

Sort by: Most helpful