1
Type T;

if (report.ReportType == 0) {
    T = typeof(ReportTempHum);
} else if (report.ReportType == 11){
    T = typeof(ReportVibration);
}

List<(Type)T> result = new List<(Type)T>();

I'm trying to assign a type into a List in terms of a reportType condition. But some errors.

How can I do this ?

Thanks in Advance!

Edit: Error; Severity Code Description Project File Line Suppression State Error CS0118 'T' is a variable but is used like a type

M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
NewPHPer
  • 238
  • 6
  • 22

4 Answers4

4

Make sure ReportTempHum and ReportVibration have the same interface.

List<IReportType> result;
        if (report.ReportType == 0) {
            result = new List<ReportTempHum>();
        } else if (report.ReportType == 11){
            result = new List<ReportVibration>();
        }

        //note to verify List is not null!
Ori Nachum
  • 588
  • 3
  • 19
  • 2
    Might be worth switching on the `report.ReportType` if there are many options too. – ScottishTapWater Jan 16 '17 at 08:14
  • Yes. That's another way to solve the problem. But I am looking for a solution by using the "Type". Thank you. – NewPHPer Jan 16 '17 at 08:14
  • Try using object (Or other closest class) then, and every time you work with the list's data, cast it to T. – Ori Nachum Jan 16 '17 at 08:46
  • 1
    @NewPHPer _But I am looking for a solution by using the "Type"_ you are trying to solve a problem in wrong way. why not use polymorphism which is most important thing in OOP, even name of your classes are telling they must have same base like `Report` class – M.kazem Akhgary Jan 16 '17 at 09:14
2

I'm afraid this can't be done:

The whole point of generics is to provide compile-time safety. Consequently, type objects cannot be used as generic parameters.

Please see answer here for more information.

Community
  • 1
  • 1
ScottishTapWater
  • 3,656
  • 4
  • 38
  • 81
0

With this code you can get a List of Type T. However, keep in mind it isn't strongly typed!

Type T;

if (report.ReportType == 0) {
    T = typeof(ReportTempHum);
} else if (report.ReportType == 11){
    T = typeof(ReportVibration);
}

var constructedListType = typeof(List<>).MakeGenericType(T);
var instance = Activator.CreateInstance(constructedListType);
abc
  • 2,285
  • 5
  • 29
  • 64
-1

Just use dynamic as the argument:

var result = new List<dynamic>();

For more inframtion see: https://msdn.microsoft.com/en-us/library/dd264736.aspx

See also this related question: How to create a List with a dynamic object type C#

Community
  • 1
  • 1
George Mamaladze
  • 7,593
  • 2
  • 36
  • 52
  • 1
    Downvoted. Usually if you have to use `dynamic` your program design is usually wrong. `dynamic` was not invented to be used in regular C# code. Generally it should only be used when working with COM, dynamic typed language libraries, ASP.NET MVC views etc. not something like this. – Bauss Jan 16 '17 at 14:30