Reputation: 315
I am thinking is there any way to assign different type of variables in single statement..?
string s = "";
int ia = 0;
int ib = 5;
// is there any short hand technique to assign all
// 3 variables in single statement..?:
s = ia = ib;
Upvotes: 0
Views: 81
Reputation: 1503509
You can do this:
string s = "";
int ia = 0;
int ib = 5;
s = (ia = ib).ToString();
I wouldn't recommend it, but it will work - ia
will be 5, and s
will be "5".
Would you really rather do that than use two statements though? I try to avoid doing too much in a single statement - brevity is not the same thing as clarity. I think most people would find this simpler to read:
string s = "";
int ia = 0;
int ib = 5;
ia = ib;
s = ib.ToString();
Or better yet:
int ib = 5;
int ia = ib;
string s = ib.ToString();
(I dislike initializing variables with values which are just going to be overwritten without ever being read.)
Upvotes: 3
Reputation: 186833
You can, but you have to explain (via operator) how to do it:
public class MyClass {
public static implicit operator MyClass(int value) {
return new MyClass();
}
}
...
int a = 2;
int b = 3;
MyClass c = a = b;
In your case int
can't be implicitly converted into String
and that is the cause of the error. The solution is an explicit conversion:
int a = 2;
int b = 3;
String c = (a = b).ToString(); // explicit conversion required
Upvotes: 2
Reputation: 81
No. But you can convert types. In you're case by example:
int a1 = 5;
String s = "" + a1;
It's not the best way. But the simplest.
Upvotes: 0
Reputation: 484
You can use shorthand technique, if datatype is same. In your case...
int ia = 0, ib = 5;
string s = ia = ib;
Upvotes: -1