Why is CS0553 a compiler error?

M

Martin Hallerdal

I tried to create a class which basically acts like union.
I have a string and an double member in my class but only
one is "active" and I want the use the "implicit" keyword
to get the "active" object. Here's the code:

public class StringDoubleVal
{
string strval;
double dblval;
bool string_active;

public void SetVal(string val)
{
strval = val; string_active = true;
}

public void SetVal(double dblval)
{
dblval = val; string_active = false;
}

public static implicit operator object(StringDoubleVal
val)
{
return val.string_active ? val.strval : val.dblval;
}
}

The problem is that since "object" is a base class of
StringDoubleVal, the compiler won't let me define an
implicit operator for the "object" type since the compiler
can perform such an operation by its self.

The problem is that the semantics in my program of the
value of a StringDoubleVal object is not the object it
contains but the currently active object contained by the
StringDoubleVal object. Why is this just not a warning
instead of an error?
 
J

Jon Skeet [C# MVP]

The problem is that the semantics in my program of the
value of a StringDoubleVal object is not the object it
contains but the currently active object contained by the
StringDoubleVal object. Why is this just not a warning
instead of an error?

How would you expect your operator to ever be invoked? Because there's
already an implicit conversion from StringDoubleVal to object, that
would always be used.

Why not just define a method GetVal which returns the appropriate
object?

(You'll then need to fix up the other problems in your code, but I'm
assuming you can do that.)
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi Martin,

I think that you need to implement a string or double operator , also you
should redefine ToString() . I think that with this 3 methods you will get
the functionality you want.

Cheers,
 
E

Eric Gunnerson [MS]

Martin,

I don't know what you want to use this class for, but I think you get the
same basic behavior from just using a variable of type "object". You can
assign either a double or a string to it, and when you reference it, it will
give you the current value as an object.

Perhaps you could explain more what you're trying to do.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://weblogs.asp.net/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
 

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