-2

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

  • what is the problem using direct `Student` ? – Mostafiz Oct 05 '16 at 15:06
  • 2
    Possible duplicate of [How do I alias a class name in C#?](http://stackoverflow.com/questions/244246/how-do-i-alias-a-class-name-in-c) – Gilad Green Oct 05 '16 at 15:06
  • @Mostafiz Because I want to declare it only once..... I have function in my controller and it starts with declaration: `IEnumerable students = GetAllStudents();` But after that Im calling few generic methods example: `students = iQueryableStudents.Where(MyGenericFunction(something, something));` With Type Alias mentioned by StriplingWarrior I can use alias and if I need to change class and aply my code somewhere else and I can change only alias (only on one place). Or do you think that this is bad idea? – user6926954 Oct 06 '16 at 08:18
  • @Gilad Green Im not sure, because before the answer from StriplingWarrior, I was not able to understand How do I alias a class name in C#? topic and find my answer in it. – user6926954 Oct 06 '16 at 08:29

1 Answers1

1

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();
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • Thank you so much StriplingWarrior! "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 students = GetAllStudents();" This was right answer for me :-) – user6926954 Oct 06 '16 at 07:06