Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Casting in C#

Tags:

c#

what is the difference as well as the pros and cons between

 LinkButton lb = (LinkButton)ctl;

and

 LinkButton lb = ctl as LinkButton;

I tried using the first one and it gives me error, then I tried the other one with the keyword as, it work just fine.

Thank You in Advance.

like image 729
Agamand The True Avatar asked Dec 06 '09 05:12

Agamand The True


People also ask

How do you type cast in Objective C?

It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets divided by count yielding a double value.

What is type casting in C?

Type Casting is basically a process in C in which we change a variable belonging to one data type to another one. In type casting, the compiler automatically changes one data type to another one depending on what we want the program to do.

What is object type casting?

Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind or Object, and the process of conversion from one type to another is called Type Casting. Before diving into the typecasting process, let's understand data types in Java.

How do you cast an object to class?

The java. lang. Class. cast() method casts an object to the class or interface represented by this Class object.


2 Answers

The first is an explicit cast, and the second is a conversion. If the conversion fails for the as keyword, it will simply return null instead of throwing an exception.

This is the documentation for each:

  • Casting and Type Conversions (C# Programming Guide)
  • as (C# Reference)

Note in the linked documentation above, they state the as keyword does not support user-defined conversions. +1 to Zxpro :) This is what a user-defined conversion is:

User-Defined Conversions Tutorial

like image 168
AaronLS Avatar answered Oct 13 '22 09:10

AaronLS


My usual guidance on using the as operator versus a direct cast are as follows:

  1. If the cast must succeed (i.e. it would be an error to continue if the cast failed), use a direct cast.
  2. If the cast might fail and there needs to be programmatic detection of this, use the as operator.

The above is true for reference types. For value types (like bool or int), as does not work. In that case, you will need to use an is check to do a "safe cast", like this:

if (x is int y)
{
   // y is now a int, with the correct value

}
else
{
    // ...
}

I do not recommend trying to catch InvalidCastException, as this is generally the sign of a programmer error. Use the guidance above instead.

like image 45
bobbymcr Avatar answered Oct 13 '22 09:10

bobbymcr