Reputation: 698
My recent code is including a lot of boxing and unboxing, as many of my variables are resolved at runtime. But I've read that boxing and unboxing is very expensive computationally, and so I want to ask if there is any other ways to box/unbox types? And is this even a good practice to use it?
Upvotes: 1
Views: 532
Reputation: 464
In that specific question I could say use the more general type, in that case string and parse it to number if its a number. More general approch is to create custom struct or use tuple with field stating what its the real answer for each case like that , but its quit ugly.
Upvotes: -1
Reputation: 32797
Use Generics
....
More info here
For example
List lst=new List();//non generic List accepts any kind of object
lst.Add(44);//this causes unnecessary boxing from int to object
lst.Add(100);//this causes unnecessary boxing from int to object
If you are sure that the list will always contain an integer you can use generics..
List<int> lst=new List<int>();
lst.Add(44);//no boxing or unboxing
lst.Add(100);//no boxing or unboxing
Upvotes: 7