-4

I want to convert the data row value to sring as follows.

userGuid = dr["user_guid"].ToString();

It may contains Guid or null(Not string empty). If it contains null i got the exception.

How can i overcome this..

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
Venkatesh
  • 192
  • 3
  • 15

4 Answers4

2

I guess you are reading from data reader.

You will have to check if the value is null or DBNull and then you can call to string method.

    string user_guid = dr["user_guid"] != DBNull.Value && dr["user_guid"] != null ? dr["user_guid"].ToString() : null ; 

Hope this helps.

Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37
1
if (dr[user_guid"] != null) {
    //whatever you want to do
} else {
    //handle the null value in some way
}

Alternatively,

dr["user_guid"]?.ToString();

The ? is what's called a "null-safe navigator".

CCD
  • 470
  • 1
  • 7
  • 19
  • I try this also i want to use this conversion in many places. So this lead too much of code.I want simple solutions – Venkatesh Jan 25 '19 at 05:28
  • 2
    This is a simple solution. If a standard check for a null value is too much, I'm not sure what exactly you could possibly be expecting. – CCD Jan 25 '19 at 05:30
  • I know this is simple question.I just want to done this by single line of code or by overriding in only one place – Venkatesh Jan 25 '19 at 05:34
0

This might be useful, one of many ways

 userGuid  = dr["user_guid"]?.ToString()?? "Default Value";

Please do replace "Default Value" with whatever you feel is appropriate according to your application logic.

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
-1

Maybe this: userGuid = dr["user_guid"].ToString() ?? throw new Exception();