开发者

Can't cast int to T, where T is bool. Is there a way to do this with C#?

I'll try to be quick, as I already made exhaustive search on this topic and I only find topics related to converting bool into int.

I built a class to handle sparse matrices. They could be filled by double, int or bool, or any other value type.

To get some matrix element at position i,j:

public T getElementValueAt(int i, int j)
{
    int ind = this.doesElemExist(i, j); 
         // returns the element index if it exists, or -1
    return (ind == -1 ? (T)(object)0 : this.elem[ind].value );
}

Before going on, one highlight on bad practices above, and other about s开发者_如何学Goparse matrices:

  1. I've been searching and found that (T)(object)0 is not a good practice, but I don't see why can't I use it here, as it works whether T is int or double;

  2. If the element I want to get is not on the list this.elem, I should return 0 typed correctly in accordance with the other elements type.

So it boils down to converting an int value (0, in this case) to a certain type T, which is a type parameter.

Any good way to do this? Any comments about this approach?

Any help would be appreciated!

Thanks in advance!


Your cast of (T)(object)0 won't work if T is double... it will throw an InvalidCastException when it tries to unbox a boxed int to double.

I suspect what you actually want is default(T), which gives the default value of whatever T is - so null for a reference type, zero for numeric types etc:

return ind == -1 ? default(T) : this.elem[ind].value;

As a side-note, I'd encourage you to try to stick to .NET naming conventions, including PascalCase for methods.

Three other options:

  • Use Nullable<T> as suggested in other answers
  • Follow the TryXXX approach of returning a Boolean value to indicate whether the element was found, and have an out parameter to receive the value itself
  • Use a modified version of the TryXXX pattern where you return a Tuple<bool, T> instead of using an out parameter


You can use default(T). But you should consider using nullable types, too. (the function should return T? where T : struct).


Use next:

Convert.ToBoolean(int);


Have you considered returning default(T) instead of 0?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜