About Generics: switch behaviour if type T is nullable

G

Giulio Petrucci

Hi there,

Please, could you take a look to the code below? My questions are inline:

public class SmartArray<T>
{
protected T[] array;

protected virtual T this[int index]
{
get
{
if ((index<0)||(index>=array.Length))
{
//what I need to do is:
//if T is nullable (I think it's the same to say that's
a ref type, roght?) then return "null"
//else rise an Exception;
}
else return array[index];
}
}
}

Any suggestion?

Thanks in advance!
Cheer,
Giulio - Italia
 
G

Giulio Petrucci

Hi myself,
Hi everybody;

My auto-suggestion is:

Giulio Petrucci ha scritto:
public class SmartArray<T>
{
protected T[] array;

protected virtual T this[int index]
{
get
{
if ((index<0)||(index>=array.Length))
{
if (typeof(T).IsValueType)
{
throw an exception;
}
else
{
return default(T); //it should be null, right?
}
}
else return array[index];
}
}
}

Any suggestion here? Is it correct that default(T) is null if T is not a
value type?

Thank you in advance,
Giulio - Italia
 
M

Marc Gravell

My suggestion here would be to raise an out-of-range exception;
default(T) will return null for ref-types, and (essentially) zero for
value-types (meaning: all fields for the struct are zero / false /
null).

Personally, I think this should behave the same way (in terms of index
violation behavior) for both ref- and value-types. Using null / 0 as a
return doesn't necessarily help, as perhaps null / 0 is a legitimate
value to pass into the SmartArray? How would you know whether you
passed a duff index?

Another option is the TryGetValue approach:

public bool TryGetValue(int index, out T value) {
if(index < 0 || index >= array.Length) {
value = default(T);
return false;
}
value = array[index];
return true;
}

Just a thought ;-p

Marc
 

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