anirudh
anirudh

Reputation: 562

How to copy a readonly object in c# and modify the copy

I have an object defined as:

readonly List<object> Params;

I need to get the values stored in the list as integers but all the casting methods I have tried like Convert class, explicit typecasting using (int) give the following error:

Unhandled Exception: System.InvalidCastException

I tried to print the elements and it gives me the integer value of the objects but copying the list keeps the readonly attribute and I am unable to use the value in my program.

Upvotes: 1

Views: 1794

Answers (3)

Felipe Oriani
Felipe Oriani

Reputation: 38626

You could use Linq to do this, for sample, add this namespace

using System.Linq;

And try to use the Cast<T> method to convert,

List<int> ints = Params.Cast<int>();

You also could use the Select method if you need to do something more specific, for sample:

List<int> ints = Params.Select(x => {

                                     // its a scope, and you can do it here...

                                     if (something)
                                        return (int) x;
                                     else if (other condition)
                                        return int.Parse(x.ToString());

                                      return x; // other custom conversions...

                                    }).ToList();

Upvotes: 2

Thomas Weller
Thomas Weller

Reputation: 11717

The readonly has no effect at all on the values stored in the list. It applies only to the List object, but not to its content. So forget about it, nothing wrong here.

Instead, there MUST be a conversion problem with at least one of the values stored in Params (btw.: the exception clearly says that)...

You may use int.TryParse(...) to find out which value it is.

Upvotes: 0

helb
helb

Reputation: 7793

If the elements in the list are strings, use

int value = int.Parse((string)Params[i]);

If the elements int the list are ints, use

int value = (int)Params[i];

Upvotes: 1

Related Questions