Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error assigning string value to integer variable

Tags:

c#

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
like image 456
Ankush Guhe Avatar asked Aug 11 '26 15:08

Ankush Guhe


2 Answers

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
like image 161
Swagata Prateek Avatar answered Aug 14 '26 09:08

Swagata Prateek


use dynamic to push datatype resolving to runtime.

    dynamic _formatedBillCode = 101; 

    _formatedBillCode="20160919_101_ank";
like image 45
A.T. Avatar answered Aug 14 '26 07:08

A.T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!