Reputation: 25287
I've got a class which looks like this
class MyClass
{
string myData;
//.....
//other fields
public static implicit operator string(MyClass c)
{
return c.myData;
}
}
Now when I assign the value of the class to a string, I get myData
's value. But in microsoft's example, to do implicit convection from MyClass
to string
, I'd have to create a new instance of MyClass
in a static method. I don't want to do this, instead I want to simply assign the string's value to myData
field.
Is this possible to do in c#, and if it is, how do I do it?
Upvotes: 2
Views: 590
Reputation: 20014
Sounds like there is no direct solution to what you need. I would suggest to try operator overloading and this would allow to perform some of the things I think you need with the understanding that = (equal) cannot be overloaded probably you would like to try += You can find additional help here:
http://msdn.microsoft.com/en-us/library/6fbs5e2h.aspx
This is a sample version:
namespace ConsoleApplication1
{
public struct MyClass
{
public string MyData {get;set;}
// Constructor.
public MyClass(string obj1):this()
{
this.MyData = obj1;
}
public static MyClass operator +(MyClass c1, string var3)
{
return new MyClass(var3);
}
public override string ToString()
{
return (System.String.Format("{0} ", this.MyData));
}
}
[System.Runtime.InteropServices.GuidAttribute("D36900FE-8902-4ED8-B961-DE5B3F3273AC")]
class Program
{
static void Main(string[] args)
{
MyClass obj1 = new MyClass();
obj1 += "Hello";
Console.ReadKey();
}
}
}
Upvotes: 3