3

initialize variable and assign int value to it and at run time assigning a string value it give error.

var _formatedBillCode = 101; 

_formatedBillCode="20160919_101_ank"; // assigning string value
2
  • 2
    var is resolved at compile time, not run time. You can't possibly change its initial type inference. Commented Sep 19, 2016 at 6:51
  • 1
    In c# "var" is different from javascript. It's not dynamic Commented Sep 19, 2016 at 6:51

4 Answers 4

3

var would infer its type in compile time. Unlike JS, var here inferred its type in compile time when you defined it with an integer first.

Later if you move with changing its type, it would throw an error because at compile time, the first type it inferred was int. You can't change it to string.

Use dynamic types for your purpose in this case like the following if you need dynamic that much:

dynamic a = 1;
Console.WriteLine(a);

// Dynamic now has a different type.
a = new string[0];
Console.WriteLine(a);

// Assign to dynamic method result.
a = Test();
Console.WriteLine(a);

// Use dynamic field.
_y = "carrot";

// You can call anything on a dynamic variable,
// ... but it may result in a runtime error.
Console.WriteLine(_y.Error);

And in your case here;

dynamic_formatedBillCode = 101; 

_formatedBillCode="20160919_101_ank"; // assigning string value
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much.. This link will also helpful link
I found this to be more concise and to the point. :)
1

use dynamic to push datatype resolving to runtime.

    dynamic _formatedBillCode = 101; 

    _formatedBillCode="20160919_101_ank";

Comments

0

As first you declaring "_formatedBillCode" as int, you cant change the type to string after that, "var" isn't dynamic, it just represent the type. you can use "dynamic" instead of "var".

Comments

0

You are trying to assign a string value to an int, that wont work without casting it. This will assign the second variable as a string with the integer cast to string:

var _formatedBillCodeInt = 101; 

var _formatedBillCode="20160919_" + _formatedBillCodeInt.ToString() + "_ank"; // assigning string value

Or did I misunderstand the question?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.