Add imlicit or explicit cast functionality to a class

H

Holger Kasten

Hello,

I would like to add imlicit or explicit cast functionality to a class.

How can I do that?

public class Varia
{
public sring _var;
}

Varia a = new Varia();
a._var = "2";
double b = 5;

How can I change it to work like this:

double res = a + b;

or to work like this:

double res = (double) a + b;

Regards,

Holger
 
G

Guest

public static explicit operator SomeOtherType(YourType X)
{
//...
}
public static implicit operator YourType(SomeOtherType X)
{
//...
}
--
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB.NET to C# Converter
Instant VB: C# to VB.NET Converter
Instant C++: C# to C++ Converter
Instant J#: VB.NET to J# Converter
 
H

Holger Kasten

David said:
public static explicit operator SomeOtherType(YourType X)
{
//...
}
public static implicit operator YourType(SomeOtherType X)
{
//...
}

Is it also possible to define multiple Other types, like:

public static implicit operator SomeOtherType(YourType X)
public static implicit operator SomeSecondOtherType(YourType X)
public static implicit operator YourType(SomeOtherType X)
public static implicit operator YourType(SomeSecondOtherType X)

I tried it and the compiler did not like it.

But how could I get the class to be casted in two differerent types
based on the other types that are beeing used in the code?

e.g.

MagicClass should do the following:

MagicClass m;

m=1;

double result = 1.23 + m;

m=2;

string result2 = "text" + m;

The results would be:

result == 2.23
result2 == text2
 
G

Guest

The first two in your example should be "explicit", not "implicit".
--
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB.NET to C# Converter
Instant VB: C# to VB.NET Converter
Instant C++: C# to C++ Converter
Instant J#: VB.NET to J# Converter
 
H

Holger Kasten

David said:
The first two in your example should be "explicit", not "implicit".

But that forces me to cast on those:

double result = 1.23 + (double) m;
string result2 = "text" + (string) m;

Is there no way to prevent that?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top