locked
Generic List doubt RRS feed

  • Question

  • User911209228 posted

    Hi ,

    I have one function name as MyGenricsWorld().I want to write a list  as 

    void MyGenricsWorld(){

    List<T> obj1;

    if(i==0){
     obj1=new List<T>(); where T=Student
    }else{

    obj1=new List<Employee>(); where T=Employee

    }

    Is possible to write the above two different way as mentioned.Both Student and Employee are two classes.

    Thanks & Regards,

    Dileep

    Thursday, May 13, 2021 1:52 PM

All replies

  • User475983607 posted

    The Generic method syntax and LINQ syntax is incorrect.  It is hard to figure out what you are trying to do given the code.

    I think that you'll be interested in reading the C# programming guide to learn how to work with Generics and LINQ.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/

    Thursday, May 13, 2021 2:26 PM
  • User303363814 posted

    What are you trying to do?

    The "code" you have shown makes no sense and would not compile.

    Friday, May 14, 2021 3:39 AM
  • User753101303 posted

    Hi,

    Seems you are trying to mix using generics with workarounds you could use when not having this feature.

    The basic idea is to write a MyMethod<T> (or MyClass<T>), T being a parameter. Then you can use MyMethod<Employee> or MyMethod<Student> where needed.

    As the type is not know, the code needs to be fairly general. if posisble you can have constraints on the T type allowing to write more specialized code.

    Thursday, May 20, 2021 9:53 AM