Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Object type casting (as / (int)) in C# [duplicate]

Tags:

c#

casting

Possible Duplicate:
What is the difference between the following casts in c#?

While am working on C#, her am doing type casting at that point I got a doubt:-

What is the difference between Object type casting for "as vs. (int)/(string)/... soon"?

Example:

int a = (int) value;

VS.

int a = value as int;

string a = (string) value;

VS.

string a = value as string;

and soon...

Can any help explain this in detail?

Thanks in advance.

like image 570
Siva Charan Avatar asked Feb 06 '26 07:02

Siva Charan


1 Answers

From msdn:

The as operator is used to perform certain types of conversions between compatible reference or nullable types.

Remarks:

The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception. Consider the following expression:

expression as type

It is equivalent to the following expression except that expression is evaluated only one time.

expression is type ? (type)expression : (type)null

Note that the as operator only performs conversions to reference or nullable types, and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

like image 149
SynerCoder Avatar answered Feb 07 '26 21:02

SynerCoder