Object Extensions

Posted on Updated on

Here is my class of object extensions I use.

using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Dahl.Core.Extensions
{
    public static partial class Extensions
    {
        public static string AsString( this object source ) { return source as string; }
        public static DateTime AsDateTime( this object source ) { return (DateTime)source; }
        public static short AsShort( this object source ) { return (short)source; }
        public static int   AsInt( this object source ) { return (int)source; }
        public static long  AsLong( this object source ) { return (long)source; }
        public static bool  AsBool( this object source ) { return (bool)source; }
        public static byte  AsByte( this object source ) { return (byte)source; }

        public static DateTime? AsNullableDateTime( this object source ) { return source as DateTime?; }
        public static short?    AsNullableShort( this object source ) { return source as short?; }
        public static int?      AsNullableInt( this object source ) { return source as int?; }
        public static long?     AsNullableLong( this object source ) { return source as long?; }
        public static bool?     AsNullableBool( this object source ) { return source as bool?; }
        public static byte?     AsNullableByte( this object source ) { return (byte?)source; }

        public static DateTime? AsDateTimeNullable( this object source ) { return source as DateTime?; }
        public static short? AsShortNullable( this object source )       { return source as short?; }
        public static int?   AsIntNullable( this object source )         { return source as int?; }
        public static long?  AsLongNullable( this object source )        { return source as long?; }
        public static bool?  AsBoolNullable( this object source )        { return source as bool?; }
        public static byte?  AsByteNullable( this object source )        { return (byte?)source; }

        public static byte AsTinyInt( this object source )               { return (byte)source; }
        public static byte? AsTinyIntNullable( this object source )       { return (byte?)source; }

        public static short AsSmallInt( this object source ) { return (short)source; }
        public static short? AsSmallIntNullable( this object source ) { return (short?)source; } 

        //-----------------------------------------------------------------------------------------
        /// <summary>
        /// Copy properties from source object into destination object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="src">copy data from this object into the specified dst object</param>
        /// <param name="dst">copy data into this object</param>
        public static void CopyFrom<T>( this T dst, T src )
        {
            PropertyInfo[] srcProperties = src.GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance );
            foreach ( PropertyInfo srcProperty in srcProperties )
            {
                if ( srcProperty.CanRead && srcProperty.CanWrite )
                {
                    PropertyInfo dstProperty = dst.GetType().GetProperty( srcProperty.Name );
                    if ( dstProperty != null )
                    {
                        object val = srcProperty.GetValue( src, null );
                        dstProperty.SetValue( dst, val, null );
                    }
                }
            }
        }

        //-----------------------------------------------------------------------------------------
        /// <summary>
        /// Makes a new object and copies 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="S"></param>
        /// <returns></returns>
        public static T GetCopy<T>( this T S )
        {
            T newObj = Activator.CreateInstance<T>();
            foreach ( PropertyInfo i in newObj.GetType().GetProperties() )
            {
                //"EntitySet" is specific to link and this conditional logic is optional/can be ignored
                if ( i.CanWrite && i.PropertyType.Name.Contains( "EntitySet" ) == false )
                {
                    object value = S.GetType().GetProperty( i.Name ).GetValue( S, null );
                    i.SetValue( newObj, value, null );
                }
            }

            return newObj;
        }

        //-----------------------------------------------------------------------------------------
        /// <summary>
        /// Perform a deep Copy of an object, object must be serializable.
        /// </summary>
        /// <typeparam name="T">The type of object being copied.</typeparam>
        /// <param name="source">The object instance to copy.</param>
        /// <returns>The copied object.</returns>
        public static T Clone<T>( this T source )
        {
            if ( !typeof( T ).IsSerializable )
            {
                throw new ArgumentException( "The type must be serializable.", nameof( source ) );
            }

            // Don't serialize a null object, simply return the default for that object
            if ( object.ReferenceEquals( source, null ) )
            {
                return default( T );
            }

            IFormatter formatter = new BinaryFormatter();
            Stream stream = new MemoryStream();
            using ( stream )
            {
                formatter.Serialize( stream, source );
                stream.Seek( 0, SeekOrigin.Begin );
                return (T)formatter.Deserialize( stream );
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *