can't make a custom struct = null

C

Chris LaJoie

I would like to be able to set my struct equal to null in a way similar to
this example:

struct TestStruct {
public int x;
}

....[other stuff]...

public void Main() {
TestStruct testvar;
testvar.x = 4;
if(testvar.x == 4) {
testvar = null;
}
...[more code]...
}

is this possible using operators? I was thinking something like this:

struct TestStruct {
public int x;

public static bool operator null(TestStruct t) {
return (t.x == 0);
}
}

that struct won't compile, but i thought it might help you to understand my
problem, and how I think it might be solved.
I know that this would be easy to do by simply using a class instead of a
struct, but I would like to be able to use other operators as well. Any
help is appreciated. Thanks,

Chris LaJoie
 
C

Christoph Nahr

I hate to say this, but there was a post on this newsgroup were
somebody overloaded a few operators and made a dummy class. The
message had subject "C# assign null to a struct" sent on Aug-1-2003

Thanks for the note. Just saw it... really quite clever!

The poster defined a dummy class and an implicit conversion from this
dummy class to the struct; then every null assignment would get mapped
to that implicit dummy conversion operator. Same for equality.

But apart from the confusion this would cause to the reader, you
cannot ever define an implicit conversion or comparison to another
reference type because that would cause an ambiguity error since the
null constant itself is typeless (or rather, fits any reference type).
 
C

Christoph Nahr

That's not strictly true; null is a literal of reference type and it can be
assigned to any variable of reference type; a reference type that has a null
value has a null value of that type.You can't assign a null value of one
type to that of another:

Correct, but the null constant itself matches any reference type.
The compiler cannot infer a specific type from the literal "null",
except by examining the type on the other side of the assignment or
equation (as in the post referenced by Michael Mayer).
 
M

Michael Mayer

Christoph Nahr said:
Oh, another thing. Does the dummy class have to public for the
implicit operators to work? I'm not sure about this but if it does,
that would be another reason not to use this method.

Yeah, it seems like it does. I just tried moving Dummy intio
MyStruct, and made it private. I got a compiler error:

error CS0057: Inconsistent accessibility: parameter type
'Namespace1.tInt.Dummy' is less accessible than operator
'Namespace1.tInt.operator ==(Namespace1.tInt, Namespace1.tInt.Dummy)'
 

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