Search code examples
c#classdynamicdeclare

C# paste T model class dynamically as variable


I want to store my model class as a variable and use it in all my code dynamically. For example I have something like this:

IEnumerable<Student> students = GetAllStudents();

Normally I must always declare and retype Student class. But I need to declare it only once and after that use it dynamically in my code. Simply I want to do something like this:

Student dynamicType;

So after that can be possible:

IEnumerable<dynamicType> students = GetAllStudents();

Can you help me to find right solution? Is it possible to do something like this? Thank you


Solution

  • It depends what you mean by "dynamic".

    If you just don't want to use the class name "Students", then you're looking for a Type Alias.

    using dynamicType = MyNameSpace.Student;
    
    ...
    IEnumerable<dynamicType> students = GetAllStudents();
    

    If you want to be able to specify which type you're dealing with from another part of code, you're looking for Generics.

    void DoSomething<T>()
    {
        IEnumerable<T> things = GetAllThings<T>();
        ...
    }
    
    ...
    DoSomething<Student>();
    

    If you want to be able to interact with the class without having any specific type associated with it, you're looking for the dynamic keyword.

    IEnumerable<dynamic> students = GetAllStudents();
    foreach(var student in students)
    {
        dynamic studentFoo = student.foo; // no type checking
    }
    

    If you want to avoid typing "Student" everywhere, but you really do want the items in your IEnumerable to be statically-checked Students, then you may just want to use the var keyword.\

    var students = GetAllStudents();