C # is cast

Source: Internet
Author: User

In peacetime development, often encounter a forced conversion, in this process often encountered a null object to the value type, if not judged in the case of the compilation will not be error, but the program is run to throw an error. Fortunately, C # provides us with the IS, which determines if an object is converted if it is formed, and returns null if it does not.

Here is an example of a specific application.

public partial class Org
{
public string OrgID {get; set;}
public string OrgName {get; set;}
public int? total{get; set;}

}

Class Program

{

static void Main (string[] args)

{

DataTable Tbldatas = new DataTable ("Datas");

DataColumn DC = null;

DC = TBLDATAS.COLUMNS.ADD ("ID", Type.GetType ("System.Int32"));

DC = TBLDATAS.COLUMNS.ADD ("OrgID", Type.GetType ("System.String"));

DC = TBLDATAS.COLUMNS.ADD ("OrgName", Type.GetType ("System.String"));

DC = TBLDATAS.COLUMNS.ADD ("Total", Type.GetType ("System.int"));

DataRow NewRow;

NewRow = Tbldatas.newrow ();

newrow["OrgID"] = "1";

newrow["OrgName"] = "Test";

newrow["Total"] = null;

TBLDATAS.ROWS.ADD (NewRow);

org org = new org ();

Org. total= tbldatas.rows[0]["Total"] as int?;

Console.WriteLine (org. Total);

}

}

In this program "org."    total= tbldatas.rows[0]["Total"] as int?; "Here is the cast, entity object public int?" total{get; set;} must be added here? No.

C # is cast

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.