Casting vs Converting an object toString, when object really is a string

后端 未结 9 2075
终归单人心
终归单人心 2020-11-28 06:13

This isn\'t really an issue, however I am curious. When I save a string in lets say an DataRow, it is cast to Object. When I want to use it, I have to cast it ToString. As f

9条回答
  •  遥遥无期
    2020-11-28 06:24

    I want to make one more comment

    If you are going to use casting: string name = (string)DataRowObject["name"] you will get an Exception: Unable to cast object of type 'System.DBNull' to type'System.String' in case if the record in the database table has null value.

    In this scenario you have to use: string name = DataRowObject["name"].ToString() or

    You have to check for null value like

    if(!string.IsNullOrEmpty(DataRowObject["name"].ToString()))
    {
    string name = (string)DataRowObject["name"];
    }
    else
    {
    //i.e Write error to the log file
    string error = "The database table has a null value";
    
    }
    

提交回复
热议问题