Struct return a value

N

Natan Vivo

I have a struct, and i always use it like "myStruct.Contents" to get
it's value... I was wondering if I can make a struct to behave like a
value.

Something like

struct MyStruct {
private int number;
get {
return number;
}
set {
number = value;
}
}

So in a function that has an int argument, i could use it directly
like "somefunction(myStruct)". myStruct returns an int, so it would
work.

i thought about operator overloading, but it doesn't seen to allow
overload = operator.

I saw that every type in .NET is declared like "public struct Int16",
"public struct Byte" and is based on System.ValueType, like structs.
so, what is the trick to do this? Is it possible?

Thanks.
 
M

Mattias Sjögren

So in a function that has an int argument, i could use it directly
like "somefunction(myStruct)". myStruct returns an int, so it would
work.

You can do this by adding an implicit conversion to int

public static implicit operator int(MyStruct ms)
{
return ms.number;
}




Mattias
 

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