views:

97

answers:

7

I am passing the parameter to the function as a var type. It is not accepting, how do I pass to the function?

Example

var Input = ................

listview1.itemsource = getinput(Input);

public List<answers>getinput(var inp)
{
................
..................
}

Here the function is not accepting the var. What can I do?

A: 

Use object in the function instead of var. Then cast it to the appropriate type within the function.

Mamta Dalal
+2  A: 

It's not accepting the third line because your function is of the type void and you try to assign the result of that function to listview1.itemsource.

halfdan
sorry it will return a List<answers>
Prabhakaran
Now you need to update your answer ...........
Pranay Rana
+5  A: 

var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.

MSDN : Implicitly Typed Local Variables

Pranay Rana
+4  A: 

var is used for type inference, not to declare a dynamic variable. Use the actual input type as the type for inp.

vc 74
A: 
public void getinput(object inp)
{
................
..................
}

As soon as C# is strongly-typed language, the compiler always knows, what real type your variable belongs to:

var Input = ....

Type of .... is always known. That's why you can't declare

var a;

and this is EXACLTLY what you are trying to do in

public void getinput(var inp)
{
    ................
    ..................
}
portland
+1  A: 

As others have said, you're mixing implicitly typed variables (type inference), and an explictly typed function signature.

What you should have is:

var Input = txtQuestion.text; // Implicitly typed variable of type string
listview1.itemsource = getinput(Input); 

// Strongly typed method taking string, returning List<answers> 
public List<answers>getinput(string question) 
{ 
    var result = new List<answers>();
    result.Add(answer);
    return result; 
} 

Sorry if this doesn't exactly match your code, but it should demonstrate what you're after.

The var keyword is used to infer the type of a variable from the right-hand side of the assignment operator. In a method's signature, there's no assignment operator, so inference can't take place. Further, you could always pass any number of types derived from a base class, which would make it difficult for the compiler to determine the correct type of the argument. (Did you mean DbReader, SqlDbReader, or IDbReader?)

Variables can be inferred. Parameters cannot.

Mike Hofer
A: 

var is just used in the JavaScript code as a variant. If you are using var then you can use string or use object.

public void getinput(object inp) 
{ 
    ................ 
    .................. 
} 


public void getinput(string inp) 
{ 
    ................ 
    .................. 
} 
Aman