1).please write an example of implicitly converting an object to string?2). please write an example explicitly converting an object to string?3).please write an example of getting around up value "55.555"

Showing Answers 1 - 6 of 6 Answers

Yogesh Rathod

  • Jan 11th, 2007
 

  1. Class Foo
  2. {
  3.  string val;
  4. //Allow Implicit conversion from Foo string to object.
  5.   public static implicit operator Foo(int args)
  6.  {
  7.   Foo foo1 = new Foo();
  8.   foo1.val = args;
  9.   return foo1;
  10.  }
  11. //Allow Explicit conversion from Foo object to string .
  12.   public static explicit operator string(Foo arg)
  13.  {
  14.    return arg.Value;
  15.  }
  16.  public override string ToString()
  17.  {
  18.   return this.Value.ToString();
  19.  }
  20. }

//Calling Code

Foo f = new Foo();

f = "Test";

string str = (string)f;

  Was this answer useful?  Yes

Objects cannot be implicitly converted to strings.The converting datatype must be similar and within the range of the to be converted data type and Only certain datatypes can be converted easily implicitly into other data types.For others it must be explicitly done.For some others conversion cannot be done both implicitly and Explicitly.Examples are:
Implicit Conversion-
int a=10;
float b;
b=a;
Explicit Conversion-
string dt="10/10/2010"
DateTime dat;
dat=Convert.ToDateTime(dt);
Conversion Impossible:
int num=10;
DateTime dat;
dat=Convert.ToDateTime(num);

Hope the examples are useful.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions