c# as keyword reference assignment
Just wondered if I have a variable constructed as follows
object a = new CustomClass;
CustomClass b = a as CustomCl开发者_如何学Cass;
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
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).
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.
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.
精彩评论