how can i return null when returning a struct

D

Digital Fart

I have the following function that returns a struct

public struct layout
{
public string str;
public int i;
}

function in some class where i loop through an arraylist of structs

public layout getLayout(string s)
{
foreach ( layout l in layoutArray)
if ( l.str == s ) return l;
}

but this does not compile because when i can't find l.str == s
what should i return then?
 
N

Nick Hounsome

Digital Fart said:
I have the following function that returns a struct

public struct layout
{
public string str;
public int i;
}

function in some class where i loop through an arraylist of structs

public layout getLayout(string s)
{
foreach ( layout l in layoutArray)
if ( l.str == s ) return l;
}

but this does not compile because when i can't find l.str == s
what should i return then?

1) return a default layout
or
2) throw an exception
or
3) make it a class and return null
 
M

Marc Gravell

In 2.0 you could return "layout?" (i.e. Nullable<layout>), but I'm not sure
its a good anwser.

Could throw an exception?

Could refactor as:

public bool TryGetLayout(string s, out layout item) {
foreach(layout l in layoutArray) {
if(l.str == s) {
item= l;
return true;
}
}
item = default(layout); // or new layout();
return false;
}

Perhaps

Marc
 
C

Clive Dixon

If you're using C# 2.0 you could use nullable types and return a 'layout?'
type (lookup nullable types and System.Nullable in the documentation)

If not, you can't have such a thing as a null struct. You would have to do
something like return an object type instead and have the caller unbox, have
a special return struct value meaning "null" or return as a ref param and
have an error code as the return of the function.
 

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