question

BitSmithy-4663 avatar image
0 Votes"
BitSmithy-4663 asked PeterFleischer-3316 answered

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

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?

windows-uwp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

PeterFleischer-3316 avatar image
0 Votes"
PeterFleischer-3316 answered

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;
    
   }


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.