Jack Kada
Jack Kada

Reputation: 25192

c# as keyword reference assignment

Just wondered if I have a variable constructed as follows

object a = new CustomClass;
CustomClass b = a as CustomClass;

and I then manipulate b by invoking b.DoWork

Do I need to assign b back to a (a=b) or am I correct in thinking they both refer to the same reference / memory address

EDIT:

Thanks for the answers - It looks like there is no need to do teh assignment (a=b) as both point to the same object

Upvotes: 0

Views: 268

Answers (3)

Oded
Oded

Reputation: 498942

This will not compile, unless you can assign CustomClass to a string. You can't assign the return type of as to a string type unless a conversion exists.

From MSDN, the as keyword is equivalent to the following (apart from expression being evaluated only once):

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

So, it returns an object of the type - in this case CustomClass. Unless you can assign CustomClass to a string, this will not compile.

Upvotes: 2

Marcin Deptuła
Marcin Deptuła

Reputation: 11957

They are references to the same object (I'm assuming that by naming your class CustomClass you actually mean it's a class (reference type), not a struct, because if it would be a structure, you can't use as operator to cast it). Also, I assume you meant to write:

object a = new CustomClass();
CustomClass b = a as CustomClass;

in your code (notice () and you can't cast it to string).

Upvotes: 2

ZombieSheep
ZombieSheep

Reputation: 29953

The short answer is that it depends if CustomClass is implemented as a reference type or a value type.

Have a look at this reference for more detail.

Upvotes: 1

Related Questions