Friday, June 1, 2012

Explicit Operators

So, you want to be able to cast your class into other classes, but you need to be able to control the casting process.


Good, we have just what the doctor ordered, explicit operators.


I did a quick demo project to explain how it works, I have a CSV file with names, numbers, dates and every time I order the records by a different column, which is a different type: string, int, DateTime.


parser.Rows.OrderBy(i => (string)i.Cell[0])



parser.Rows.OrderBy(i => (int?)i.Cell[1])



parser.Rows.OrderBy(i => (DateTime?)i.Cell[2])


And the class:


        /// <summary>
        /// Parsed Cell
        /// </summary>
        public class Cell
        {
            /// <summary>
            /// Column Number of cell
            /// </summary>
            public int ColumnNumber;

            /// <summary>
            /// Text value of cell
            /// </summary>
            public string Value;

            /// <summary>
            /// Explicit cast to int
            /// </summary>
            /// <param name="cell"></param>
            /// <returns></returns>
            public static explicit operator int(Cell cell)
            {
                return Convert.ToInt32(cell.Value);
            }
            
            /// <summary>
            /// Explicit cast to int?
            /// </summary>
            /// <param name="cell"></param>
            /// <returns></returns>
            public static explicit operator int?(Cell cell)
            {
                int retval;
                if (int.TryParse(cell.Value, out retval))
                    return retval;

                return null;
            }

            /// <summary>
            /// Explicit cast to string
            /// </summary>
            /// <param name="cell"></param>
            /// <returns></returns>
            public static explicit operator string(Cell cell)
            {
                return cell.Value;
            }

            /// <summary>
            /// Explicit cast to DateTime
            /// </summary>
            /// <param name="cell"></param>
            /// <returns></returns>
            public static explicit operator DateTime(Cell cell)
            {
                return DateTime.Parse(cell.Value);
            }

            /// <summary>
            /// Explicit cast to DateTime?
            /// </summary>
            /// <param name="cell"></param>
            /// <returns></returns>
            public static explicit operator DateTime?(Cell cell)
            {
                DateTime retval;
                if (DateTime.TryParse(cell.Value, out retval))
                    return retval;

                return null;
            }
        }


And for the demo project:
https://github.com/drorgl/ForBlog/tree/master/CSVParser

You can generate your own test data with this nice website:
http://www.generatedata.com/#generator



No comments:

Post a Comment