Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, Is it possible to recast an object and access methods and properties without creating new object variable

C#, Is it possible to recast an object and access methods and properties without creating new object variable?

For example:

foreach (object o in collection)
{
    if (o is MyType)
        {
            (MyType)o.MyProperty = x
        }
 }

Currently, I have to re-cast o to another variable of MyType [ex: MyType m = (MyType)o ] in order to access methods or properties of MyType. It seems wasteful, so I'm wondering if I'm missing some mechanic that will allow me to skip the declaration of a new object variable.

like image 233
Jake Shakesworth Avatar asked Dec 12 '25 17:12

Jake Shakesworth


1 Answers

Your code doesn't work because . has higher precedence than the cast. So you need to add parentheses:

foreach (object o in collection) 
{ 
    if (o is MyType) 
        { 
            ((MyType)o).MyProperty = x; 
        } 
 } 
like image 132
Steve Avatar answered Dec 15 '25 21:12

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!