Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing type 'var' into a method in C# [duplicate]

Tags:

c#

I have some sub queries which are of data type var. These are getting working on a data table. I would like to pass these into another method, how can i do that? Ex:

    var subquery1= from results in table.AsEnumerable()
               where //some condition
               select new
               {
                  column1=results.field1,
                  column2 = results.field2
                  etc.,
               }
     var subquery2= from results in table.AsEnumerable()
               where //different condition
               select new
               {
                  column1=results.field1,
                  column2 = results.field2
                  etc.,
               }

Now, I would like to define some method to pass these subquery1, subquery2 as variables. ex:

void updategrid(var queries)
          {
          //some logic
           }

And execute the method:

updategrid(subquery1);
updategrid(subquery2);

When i try to use var in the method when defining it is not liking it. Please help me in how to do that. Thanks.

like image 732
svs Avatar asked Jan 11 '13 15:01

svs


2 Answers

Use Object or dynamic

void updategrid(object queries)

void updategrid(dynamic queries)

var -> static type that is determined by the right side of expression. Cannot be used as parameter/return type

object -> Base class for all .NET types.

dynamic -> The type is resolved at runtime. Hence compile time checks are not made, and intellisense is not available. It has performance cost also.

like image 200
Tilak Avatar answered Oct 21 '22 09:10

Tilak


void updategrid(var queries)

Is not valid C#.

var is syntactic sugar - the variable has a type, but you don't need to declare it if the compiler can statically determine what it should be.

With a parameter, the compiler doesn't have enough information to determine the type.

Similarly, you can't declare a variable with var without assignment:

var something;

You will need to ensure the types of subquery1, subquery2 and the parameter to updategrid are all the same.

like image 32
Oded Avatar answered Oct 21 '22 08:10

Oded