Ankush Guhe Ankush Guhe - 1 month ago 5x
C# Question

Error assigning string value to integer variable

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


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;

// Dynamic now has a different type.
a = new string[0];

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

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

// You can call anything on a dynamic variable,
// ... but it may result in a runtime error.

And in your case here;

dynamic_formatedBillCode = 101; 

_formatedBillCode="20160919_101_ank"; // assigning string value