473,466 Members | 1,613 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Boxing & Unboxing

Airslash
221 New Member
Hello,

I'm still working on my self-aware classes for database communication, and I have an issue that I'd like to see clarified.

i've been reading some more about the C# programming, and came across the stuff regarding "boxing and unboxing" of variables. And if I understand that concept correctly, I think it applies to the following situation:

I have a class called Cell. It holds a string for the columnname and 2 objects for the value and the old_value.
I'm sure that if I obtain and store the data each time in these objects, I'm bound to disaster performance wise with the boxing & unboxing concept.
Is there a solution that allows me to store any kind of data in a variable without having to go around the boxing & unboxing stuff?
May 11 '10 #1
6 2437
Airslash
221 New Member
I've worked around the problem by using Generics, but I think i've run into another problem now :)

Consider my class Cell :

Expand|Select|Wrap|Line Numbers
  1.    public class Cell<T> : ICloneable, IComparable, ISerializable, IXmlSerializable
  2.     {
  3.         #region Constructors
  4.  
  5.         /// <summary>
  6.         /// Creates a new instance of the Cell class without setting
  7.         /// a name of value.
  8.         /// </summary>
  9.         public Cell()
  10.             : this(String.Empty, default(T))
  11.         { }
  12.  
  13.         /// <summary>
  14.         /// Creates a new instance of the Cell class with the specified
  15.         /// name. The value will be set to null.
  16.         /// </summary>
  17.         /// <param name="name"></param>
  18.         public Cell(string name)
  19.             : this(name, default(T))
  20.         { }
  21.  
  22.         /// <summary>
  23.         /// Creates a new instance of the Cell class with the specified name
  24.         /// and value.
  25.         /// </summary>
  26.         /// <param name="name">The name of the Cell.</param>
  27.         /// <param name="value">The raw value of the Cell.</param>
  28.         public Cell(string name, T value)
  29.         {
  30.             this.Name = name;
  31.             this.Value = value;
  32.             this.OldValue = default(T);
  33.         }
  34.  
  35.         /// <summary>
  36.         /// Creates a new instance of the Cell class with the information
  37.         /// passed from the serialization context.
  38.         /// </summary>
  39.         /// <param name="info"></param>
  40.         /// <param name="contect"></param>
  41.         public Cell(SerializationInfo info, StreamingContext contect)
  42.         {
  43.             this.Name = info.GetString("Cell_Name");
  44.             this.Value = (T)info.GetValue("Cell_Value", typeof(T));
  45.             this.OldValue = (T)info.GetValue("Cell_OldValue", typeof(T));
  46.         }
  47.  
  48.         #endregion
  49.  
  50.         #region Properties
  51.  
  52.         /// <summary>
  53.         /// Gets or sets the name of the Cell.
  54.         /// </summary>
  55.         public string Name
  56.         {
  57.             get { lock (this) { return m_name; } }
  58.             set { lock (this) { m_name = value; } }
  59.         }
  60.  
  61.         /// <summary>
  62.         /// Gets or sets the raw value of the Cell.
  63.         /// </summary>
  64.         public T Value
  65.         {
  66.             get { lock (this) { return m_value; } }
  67.             set { lock (this) { this.OldValue = m_value; m_value = value; } }
  68.         }
  69.  
  70.         /// <summary>
  71.         /// Gets whether the contents of this Cell have been modified since
  72.         /// it's creation.
  73.         /// </summary>
  74.         public bool Modified
  75.         {
  76.             get { lock (this) { return EqualityComparer<T>.Default.Equals(m_old_value); } }
  77.         }
  78.  
  79.         /// <summary>
  80.         /// Gets or sets the old value of the Cell.
  81.         /// This function supports the NexusLink framework and should not be used/visible in your code.
  82.         /// </summary>
  83.         internal T OldValue
  84.         {
  85.             get { lock (this) { return m_old_value; } }
  86.             set { lock (this) { m_old_value = value; } }
  87.         }
  88.  
  89.         #endregion
  90.  
  91.         #region Private Fields
  92.  
  93.         private string m_name;      // The name of the Cell.
  94.         private T m_value;          // The raw value of the Cell.
  95.         private T m_old_value;      // The raw old value of the Cell.
  96.  
  97.         #endregion
  98.  
  99.         #region ICloneable Members
  100.  
  101.         /// <summary>
  102.         /// Creates a deep copy of the current Cell by copying over
  103.         /// all the internal datamembers in a bit-wise fashion.
  104.         /// </summary>
  105.         /// <returns>A Clone of the current Cell with the exact same data.</returns>
  106.         public object Clone()
  107.         {
  108.             // Surround the function call with a lock so our datamembers cannot
  109.             // be changed by another thread during the copy process.
  110.             lock (this)
  111.             {
  112.                 // To perform the deep clone operation we need a memorystream
  113.                 // and a formatter.
  114.                 MemoryStream sm = new MemoryStream();
  115.                 IFormatter bf = new BinaryFormatter();
  116.  
  117.                 // Serialize our object into memory.
  118.                 bf.Serialize(sm, this);
  119.  
  120.                 // Position the cursor in the memorystream at the beginning.
  121.                 sm.Seek(0, SeekOrigin.Begin);
  122.  
  123.                 // Deserialize our object into something new.
  124.                 Cell<T> copy = (Cell<T>)bf.Deserialize(sm);
  125.  
  126.                 // Release the memory.
  127.                 sm.Close();
  128.  
  129.                 // Return the copy.
  130.                 return copy;
  131.             }
  132.         }
  133.  
  134.         #endregion
  135.  
  136.         #region IComparable Members
  137.  
  138.         /// <summary>
  139.         /// Compares two Cells against each other based upon their name.
  140.         /// </summary>
  141.         /// <param name="obj">The object to compare against.</param>
  142.         /// <returns>Less then zero if the name is less then the passed Cell's name; zero if both names are equal; Greather then zero if the name if more then the passed Cell's name.</returns>
  143.         /// <exception cref="ArgumentException">The object 'obj' is not of type Cell.</exception>
  144.         public int CompareTo(object obj)
  145.         {
  146.             // Surround the function call with a lock so our data
  147.             // does not get altered by another thread during the call.
  148.             lock (this)
  149.             {
  150.                 // Convert the passed object to type Cell.
  151.                 Cell<T> temp = obj as Cell<T>;
  152.  
  153.                 // First check if the passed object is of the same type.
  154.                 if (temp == null)
  155.                 {
  156.                     throw new ArgumentException("The passed object 'obj' is not of type Cell");
  157.                 }
  158.  
  159.                 // Cells are considered identical if there names match. Otherwise they
  160.                 // will be sorted in order of their name.
  161.                 return this.Name.CompareTo(temp.Name);
  162.             }
  163.         }
  164.  
  165.         #endregion
  166.  
  167.         #region ISerializable Members
  168.  
  169.         /// <summary>
  170.         /// Allows the object to be serialized for transport or storage. This function stores
  171.         /// all the required information from the object into the SerializationInfo object.
  172.         /// The StreamingContext provides additional information about the destination of
  173.         /// the serialization.
  174.         /// </summary>
  175.         /// <param name="info">The SerializationInfo object to hold the data.</param>
  176.         /// <param name="context">Additional information about the destination of the serialization.</param>
  177.         public void GetObjectData(SerializationInfo info, StreamingContext context)
  178.         {
  179.             // Surround our call with a lock, because we don't want our
  180.             // data changed during the retrieval process.
  181.             lock (this)
  182.             {
  183.                 // Add our data to the SerializationInfo object.
  184.                 info.AddValue("Cell_Name", this.Name);
  185.                 info.AddValue("Cell_Value", this.Value);
  186.                 info.AddValue("Cell_OldValue", this.OldValue);
  187.             }
  188.         }
  189.  
  190.         #endregion
  191.  
  192.         #region IXmlSerializable Members
  193.  
  194.         /// <summary>
  195.         /// Only used by the DataSet in .NET, therefor this function always
  196.         /// returns null because we're not a DataSet.
  197.         /// </summary>
  198.         /// <returns>null</returns>
  199.         public System.Xml.Schema.XmlSchema GetSchema()
  200.         {
  201.             return null;
  202.         }
  203.  
  204.         /// <summary>
  205.         /// This function will read out the XML and rebuild the entire Cell object
  206.         /// based upon the information stored in the XML.
  207.         /// </summary>
  208.         /// <param name="reader">The XmlReader to parse the XML document.</param>
  209.         public void ReadXml(System.Xml.XmlReader reader)
  210.         {
  211.             // Consume the root element first of the XML file.
  212.             reader.ReadStartElement();
  213.  
  214.             // Read the first attribute of the root element, this should be the name
  215.             // of our Cell.
  216.             this.Name = reader.GetAttribute("name");
  217.  
  218.             // Read the value of our cell next.
  219.             reader.ReadStartElement("value");
  220.             this.Value = (T)reader.ReadContentAs(typeof(T), null);
  221.             reader.ReadEndElement();
  222.  
  223.             // Read the old value of cell.
  224.             reader.ReadStartElement("oldvalue");
  225.             this.OldValue = (T)reader.ReadContentAs(typeof(T), null);
  226.             reader.ReadEndElement();
  227.  
  228.             // Consume the root end tag.
  229.             reader.ReadEndElement();
  230.         }
  231.  
  232.         /// <summary>
  233.         /// This function will write out the attributes of our class
  234.         /// into the XML file. Because we wish that a Cell is represented
  235.         /// as a single element, we will add the values as attributes.
  236.         /// </summary>
  237.         /// <param name="writer">The XmlWriter to write the XML file.</param>
  238.         public void WriteXml(System.Xml.XmlWriter writer)
  239.         {
  240.             // Write the name of our cell as an attribute in the root tag.
  241.             // We always assume the root tag to be present.
  242.             writer.WriteAttributeString("name", this.Name);
  243.  
  244.             // Now we will write the elements to contain the values of our Cell.
  245.             // These will be childnodes of the Cell element.
  246.             writer.WriteStartElement("value");
  247.             writer.WriteValue(this.Value);
  248.             writer.WriteEndElement();
  249.  
  250.             // As last step we write the "old value" of the Cell element.
  251.             // Just like the "value" it's a child of Cell.
  252.             writer.WriteStartElement("oldvalue");
  253.             writer.WriteValue(this.OldValue);
  254.             writer.WriteEndElement();
  255.  
  256.             // We never write the root elements.
  257.         }
  258.  
  259.         #endregion
  260.     }
  261.  

Now I have a class Row, that holds a generic list of type Cell<T>, but I'm confused on how to properly work with or define the type T for Cell in my row.

Expand|Select|Wrap|Line Numbers
  1.     class Row : ICloneable, ISerializable, IXmlSerializable
  2.     {
  3.         public Row()
  4.         { }
  5.  
  6.         internal Row(List<Cell<Type>> cells)
  7.         { }
  8.  
  9.         public bool Add(Cell<Type> cell)
  10.         { }
  11.  
  12.         public bool Remove(Cell<Type> cell)
  13.         { }
  14.  
  15.         public bool Contains(Cell<Type> cell)
  16.         { }
  17.  
  18.         internal bool ContainsModifiedCells()
  19.         { }
  20.  
  21.         public Cell<Type> this[int index]
  22.         { 
  23.             get{}
  24.         }
  25.  
  26.         public Cell<Type> this[string name]
  27.         {
  28.             get{}
  29.         }
  30.  
  31.         public int Count
  32.         {
  33.             get { lock (this) { return m_cells.Count; } }
  34.         }
  35.  
  36.         private List<Cell<Type>> m_cells;
  37.  
Is this correct? The compiler is not complaining, but it looks so odd and confusing....
May 11 '10 #2
Plater
7,872 Recognized Expert Expert
You are changing <Type> to the type you want right?
private List<Cell<Type>> m_cells;
May 11 '10 #3
Airslash
221 New Member
So using the "Type" class from reflection instead of just "T" will work?

The idea is to have a list of Cell<T> objects. Each Cell in the list should be able to have a different type at runtime. That's what I'm trying to achieve. I don't want to make my Row class Generic or type bound either, I just want to be able to do this for example:

Expand|Select|Wrap|Line Numbers
  1. Row r = new Row'();
  2. r.AddCell(new Cell<int>("ID"));
  3. r.AddCell(new Cell<string>("Name"));
  4. r.AddCell(new Cell<object>("Image"));
  5. r.AddCell(new Cell<int>("Amount"));
  6. r.Commit();
  7.  
That's what I'm trying to achieve, so I can reuse the single Cell class without having to worry about bocxing.unboxing values when retrieving info from the database. Hope I made it clear what I'm trying to achieve.
May 11 '10 #4
Plater
7,872 Recognized Expert Expert
Yeah I can see what you want, but List<Cell<Type>> will force your Cell objects to contain the Type class (or derived classes) and not Type T.

At some point I think you are going to have to box/unbox your entries if you want a collection with different types in it.
May 11 '10 #5
Airslash
221 New Member
any way around the issue then?

I tried defining them it as
Expand|Select|Wrap|Line Numbers
  1. List<Cell<T>> m_cells;
  2.  
But this gives me compiler errors, saying something about namespace T not recognised.
Surely there must be a way to implement this without making my Row class Generic, or type bound?
May 12 '10 #6
Plater
7,872 Recognized Expert Expert
If it were possible, I would think there would already be a class that does it?
You've pretty much just re-created the DataRow object right now
May 12 '10 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Justine | last post by:
Hi All, I need a small clarification with regard to Boxing. struct Currency { ......... } Currency Bal = new Currency; Object Obj = Bal;
24
by: ALI-R | last post by:
Hi All, First of all I think this is gonna be one of those threads :-) since I have bunch of questions which make this very controversial:-0) Ok,Let's see: I was reading an article that When...
16
by: Ed A | last post by:
Hi all: I'm using a struct of type Point that is being passed on to a method as a refrence type (boxing), the UpdatePoint method changes the coordinates of this point as such: Point p = new...
94
by: Peter Olcott | last post by:
How can I create an ArrayList in the older version of .NET that does not require the expensive Boxing and UnBoxing operations? In my case it will be an ArrayList of structures of ordinal types. ...
19
by: ahjiang | last post by:
hi there,, what is the real advantage of boxing and unboxing operations in csharp? tried looking ard the internet but couldnt find any articles on it. appreciate any help
161
by: Peter Olcott | last post by:
According to Troelsen in "C# and the .NET Platform" "Boxing can be formally defined as the process of explicitly converting a value type into a corresponding reference type." I think that my...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.