Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlDataReader GetChar(int index) method

Specified in MSDN:

MSDN - SqlDataReader GetChar Except that method is marked with

[EditorBrowsable(EditorBrowsableState.Never)]

attribute and while you can code -> compile it, when you run the method it throws a "method not supported" exception.

Is there any way to then read a single char from a reader without using the (buffer required) GetChars method or reading it in as a string and then getting the [0] character?

(Also, shouldn't those methods be either hidden or marked with something on MSDN stating you shouldn't use them?)

EDIT:

As pointed out by Daniel A. White, down in the remarks section there's a single line saying the method is not supported for SqlClient.

like image 673
Rostov Avatar asked Jun 06 '13 18:06

Rostov


People also ask

How to Get data from SqlDataReader in c#?

To retrieve data using a DataReader, create an instance of the Command object, and then create a DataReader by calling Command. ExecuteReader to retrieve rows from a data source.

Why we use SqlDataReader in c#?

The SqlDataReader is used to read a row of record at a time which is got using SqlCommand. It is read only, which means we can only read the record; it can not be edited. And also it is forward only, which means you can not go back to a previous row (record).


2 Answers

While I could have used:

reader.GetString(colIndex)[0]

I instead opted for:

var buffer = new char[1];
reader.GetChars(colIndex, 0, buffer, 0, 1);
like image 86
Rostov Avatar answered Sep 28 '22 11:09

Rostov


Because SqlDataReader implements IDataReader, it has a GetChar() method. But on SqlDataReader, the implementation of that is just to throw a NotImplementedException. SqlDataReader is marked so as to not offer GetChar() in the intellisense, although if you type in GetChar() onto the end of a SqlDataReader, you'll see that it compiles but at runtime you get the NotImplementedException.

All rather disappointing, as it seems to me that it would only have taken a few lines of code for the .Net team to have implemented GetChar().

Happily, by using extension methods, we can add our own GetChar() method to SqlDataReader. As GetChar() is taken already (although only implemented with a NotImplmentedException), we have to call it something other than GetChar(). I called it GetSingleChar():

internal static class ExtensionMethods
{
    internal static char GetSingleChar(this SqlDataReader reader, int columnIndex)
    {
        System.Data.SqlTypes.SqlChars val = reader.GetSqlChars(columnIndex);
        if (val.Length != 1)
        {
            throw new ApplicationException(
                "Expected value to be 1 char long, but was "
                + val.Length.ToString() + " chars long.");
        }
        return val[0];
    }
}
like image 26
Jinlye Avatar answered Sep 28 '22 13:09

Jinlye