Link to home
Start Free TrialLog in
Avatar of Cyber-Storm
Cyber-Storm

asked on

C# Method Return Structure by Reference

Hi,

Is it possible to return a structure by reference?

Example:
public struct myStruct
{
string foo;
string bar;
}

public myStruct[] Instances;
Instances = new myStruct[1];
Instances[0].foo = "Hello";
Instances[1].bar = "World";

public myStruct getInstance()
{
return Instances[0];
}

myStruct instance = getInstance();

This will return a copy of the structure, I want it to return the reference to it so I can do this:
myStruct instance = getInstance();
instance.foo = "Source";
instance.bar = "Code";

I know I can pass instance as a reference variable:
myStruct instance = new MyStruct();
getInstance(ref instance);

But I don't want to do this if I don't have to.

Many thanks,
Storm
SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Cyber-Storm
Cyber-Storm

ASKER

Yeah, wouldn't want to go the unsafe route, how would I fix the below then?
public struct myStruct
{
string foo;
string bar;
}

public myStruct[] Instances;
Instances = new myStruct[1];
Instances[0].foo = "Hello";
Instances[1].bar = "World";

public int getInstanceID()
{
return 0;
}

Now am forced to do this
Instances[getInstanceID()].foo = "Source";
Instances[getInstanceID()].bar = "Code";
but I want to do something like this instead
myStruct instance = Instances[getInstanceID()];

so that I can do this:
instance.foo = "Source";
instance.bar = "Code";
Thanks
Thanks DaTribe,
We posted at the same time so I didn't see yours.  I wouldn't want to go the object route as it's concidered a "dirty" solution.  But I fully understand your logic and while I know doing it this way would work, I was hoping for a "cleaner" solution and was reserving that as my last resort if I didn't come right here.
The link I provided explains that it is not possible for two structs to have the same address so I do not think the approach you require is possible.

http://msdn.microsoft.com/en-us/library/dd183752.aspx

DaTribe
I implemented a class instead of a structure and exposed the variables as automatic properties, I think this is the cleanest and most elegant solution in this case.

Both good options you guys put forth as well, thanks guys.