yogeshkmrsoni
yogeshkmrsoni

Reputation: 315

Is there any way to assign diffrent type variables in single statement..?

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

Answers (4)

Jon Skeet
Jon Skeet

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

Dmitrii Bychenko
Dmitrii Bychenko

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

Uwe Schmidt
Uwe Schmidt

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

Krishnandu Sarkar
Krishnandu Sarkar

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

Related Questions