merp
merp

Reputation: 282

Generic list in C# 4.0

I'm trying to create a generic list using C# and .NET 4.0

List<var> varlist = new List<var>(); This code produces the error "The contextual keyword 'var' may only appear in a local variable declaration"

The reason being is because I want to do something like this:

List<var> varList = new List<var>(); // Declare the generic list
List<Object1> listObj1;              // List of Object1
List<Object2> listObj2;              // List of Object2

varList = listObj1;                  // Assign the var list to list of Object1

varList = listObj2;                  // Re-assign the var list to the list of Object2

Is there any way to do this in C# .NET 4.0?

Upvotes: 3

Views: 286

Answers (3)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

If you want a generic list, then you have to define that generic type somewhere. I'm assuming this is at classlevel:

class MyClass<T> {
    List<T> someGenericList = new List<T>();
}

Or you use the baseclass for all types:

List<object> someGenericList = new List<object>();

Or you make it dynamic (only use this when you're absolutely sure you need it)

List<dynamic> someGenericList = new List<dynamic>();

Or lastly: you adapt your design. Typically if you have to define such a high level type of collection, you have options to refactor it in a way that it allows you to use more of the common type. If you want feedback on this then you would have to give more information concerning the context.

Don't forget to read MSDN: An introduction to C# generics.

The reason your code doesn't work is because var is a keyword and not a type. It substitutes itself for the actual type of the expression that follows and thus allows you to get right to creating your expression instead of having to explicitly define it first. Therefore in order to use it, there actually has to be an expression that follows it.

Upvotes: 9

All Blond
All Blond

Reputation: 822

Change var to something which is not keyword in C#. For example

 List<object> varlist = new List<object>();

Upvotes: 0

PetarPenev
PetarPenev

Reputation: 339

You cannot define method parameters with var because the var part must be resolved at compile-time and the compiler cannot do that. Your best bet is to use:

List<dynamic> dynamicList = new List<dynamic>();

which, I think, should be resolved during compile time to its equivalent

List<object> dynamicList = new List<object>();

Then, every time you are accessing the members of the list, in order to use them to do something meaningful, you will have to explicitly cast them to your required type. You have to consider whether it is worth to do so. It would be better if you can either:

  1. Use different lists for different types
  2. Use a base class with a relevant abstract or virtual method that is being overriden with the expected behavior.

Upvotes: 1

Related Questions