.Net C# Extension methods on instances

A quick demo on how to use extension methods (static) on instances of classes

using System;
using System.Reflection;

namespace CsharpExtensionMethodsOnInstanceDemo
{
    class CsharpExtensionMethodsOnInstanceExample
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        static void Main()
        {
            const int anInteger = 98765;

            anInteger.DisplayAssembly();

            var web = new System.Net.HttpListener();

            web.DisplayAssembly();

            Console.ReadKey();
        }
    }

    /// <summary>
    /// Simple extension method
    /// </summary>
    static class Extensions
    {
        public static void DisplayAssembly(this object input)
        {
            Console.WriteLine("In Assembly: {0}",Assembly.GetAssembly(input.GetType()).GetName().Name);
        }
    }
}

Returns:

In Assembly: mscorlib
In Assembly: System

.Net C# System.GC

A quick demo of what can be found in System.GC.

using System;

namespace CsharpGCDemo
{
    class CsharpGCExample
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        static void Main()
        {
            Console.WriteLine("Bytes on the heap: {0}", GC.GetTotalMemory(false));
            
            Console.WriteLine("Object generations: {0}", GC.MaxGeneration+1);

            var obj = new {Name = "a", Age = "10"};

            Console.WriteLine("Generation of object: {0}", GC.GetGeneration(obj));

            Console.ReadKey();
        }
    }
}

Returns:

Bytes on the heap: 29468
Object generations: 3
Generation of object: 0

.Net C# nested namespaces

It’s possible to nest namespaces with namespaces in an program, a quick demo of nesting below:

using System;

namespace CsharpNestedNamespacesDemo
{
    namespace LevelOneNestedNameSpace
    {
        namespace LevelTwoNestedNameSpace
        {
            class CsharpNestedNamespacesExample
            {
                /// <summary>
                /// Defines the entry point of the application.
                /// </summary>
                private static void Main()
                {
                    var tl = new TopLevelClass();
                    Console.WriteLine(tl.Show());

                    var l1 = new LevelOneClass();
                    Console.WriteLine(l1.Show());

                    Console.ReadKey();
                }
            }
        }

        /// <summary>
        /// Class at level 1
        /// </summary>
        public class LevelOneClass
        {
            public string Show()
            {
                return "Class at level One";
            }
        }
    }

    /// <summary>
    /// Class at top level
    /// </summary>
    public class TopLevelClass
    {
        public string Show()
        {
            return "Class at top level";
        }
    }
}

Returns:

Class at top level
Class at level One

.Net C# out modifier

A Quick example of the C# out modifier.

using System;

namespace CsharpOutModifierDemo
{
    class CsharpOutModifierExample
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        static void Main()
        {
            int result;
            Multiply(10, 10, out result);
            Console.WriteLine("multiplication result: {0} ", result);
            Console.ReadKey();
        }

        /// <summary>
        /// Multiplies the specified values.
        /// </summary>
        /// <param name="x">Input integer.</param>
        /// <param name="y">Input integer.</param>
        /// <param name="result">Output result.</param>
        private static void Multiply(int x, int y, out int result)
        {
            result = x*y;
        }
    }
}

Returns:

100

.Net C# partial classes

A quick demo of using a partial class to split class functionality into different code blocks.

using System;

namespace CsharpPartialClassDemo
{
    class CsharpPartialClassExample
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        static void Main()
        {
            var partialDemo = new PartialDemo {Name = "This is a partial class demo."};

            Console.WriteLine(partialDemo.WriteName());

            Console.ReadKey();
        }
    }

    /// <summary>
    /// Partial demo class with property
    /// </summary>
    public partial class PartialDemo
    {
        public string Name { private get; set; }
    }

    /// <summary>
    /// Partial demo class with method
    /// </summary>
    /// <returns>String</returns>
    public partial class PartialDemo
    {
        public string WriteName()
        {
            return Name;
        }
    }
}

Returns:

This is a partial class demo.

.Net C# lock statement

A lock can be performed by locking a critical section via a mutual-exclusion lock, then executing a statement and releasing the lock on completion. Here’s a quick example of a simple lock below:

using System;

namespace ChsharpLockDemo
{
    /// <summary>
    /// Locking example
    /// </summary>
    public class ChsharpLockExample
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        static void Main()
        {
            var adder = new Adder()
                .AddAmount(10);

            Console.WriteLine(adder);

            Console.ReadKey();
        }
    }

    /// <summary>
    /// Adder class
    /// </summary>
    public class Adder
    {
        private int _amount = 20;

        private readonly Object _lock = new Object();

        public int AddAmount(int amount)
        {
            lock (_lock)
            {
                _amount += amount;
            }

            return _amount;
        }
    }
}

Returns:

30

.Net C# member shadowing

Member shadowing is a language feature that is the opposite of method overriding. When shadowing, compilation will generate the following error:

'CsharpMemberShadowingExample.ShadowDemo.Do()' hides inherited member 'CsharpMemberShadowingExample.ShadowDemoBase.Do()'. Use the new keyword if hiding was intended.

The following code demonstrates the use of the new keyword to resolve this:

using System;

namespace CsharpMemberShadowingExample
{
    public class CsharpMemberShadowingDemo
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        static void Main()
        {
            var shadowDemo = new ShadowDemo();
            shadowDemo.Do();
        }
    }

    /// <summary>
    /// ShadowDemoBase class
    /// </summary>
    public class ShadowDemoBase
    {
        public void Do()
        {
            Console.WriteLine("Do something..");
        }
    }

    /// <summary>
    /// ShadowDemo class
    /// </summary>
    public class ShadowDemo : ShadowDemoBase
    {
        // New keyword used to resolve warning
        public new void Do()
        {
            Console.WriteLine("Doing something..");
        }
    }
}

.Net C# Custom Exception class

A quick example of a custom exception in .Net.

using System;

namespace CsharpCustomExceptionDemo
{
    public class CsharpCustomExceptionExample
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <exception cref="CsharpCustomExceptionDemo.MyCustomException">Bad bad bad..;Bad program</exception>
        /// <exception cref="DateTime"></exception>
        private static void Main()
        {
            try
            {
                throw new MyCustomException("Bad bad bad..", "Bad program", DateTime.Now);
            }
            catch (MyCustomException ex)
            {
                Console.WriteLine("{0} {1} {2}", ex.Message, ex.ErrorCause, ex.ErrorTime);
            }

            Console.ReadKey();
        }
    }

    /// <summary>
    /// Custom exception class
    /// </summary>
    public class MyCustomException : ApplicationException
    {
        public DateTime ErrorTime { get; set; }

        public string ErrorCause { get; set; }

        private readonly string _messageDetail = String.Empty;

        /// <summary>
        /// Initializes a new instance of the <see cref="MyCustomException"/> class.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="cause">The cause.</param>
        /// <param name="errorTime">The error time.</param>
        public MyCustomException(string message, string cause, DateTime errorTime)
        {
            _messageDetail = message;

            ErrorCause = cause;

            ErrorTime = errorTime;
        }

        /// <summary>
        /// Gets a message that describes the current exception.
        /// </summary>
        /// <returns>The error message that explains the reason for the exception, or an empty string("").</returns>
        public override string Message
        {
            get { return string.Format("Custom error message: {0}", _messageDetail); }
        }
    }
}

Returns:

Custom error message: Bad bad bad.. Bad program 05/12/2013 19:27:03

.Net C# Anonymous types

A quick demo of an anonymous type in C#.

using System;

namespace CsharpAnonymousTypeDemo
{
    class CsharpAnonymousTypeExample
    {
        static void Main()
        {
            var person = new {Name = "Developer", Occupation = "C# Developer", Location = "The Internet"};

            Console.WriteLine("{0} {1} {2}", person.Name,person.Occupation,person.Location);

            Console.ReadKey();
        }
    }
}

Returns:

Developer C# Developer The Internet

.Net C# case insensitive character replacement

I had a requirement for a case insensitive string replacement routine, having found this article (How can I do a case Insensitive String.Replace in c#?) in stackoverflow I tidied it up a bit for a quick demo.

using System;

namespace CsharpInsensitiveReplaceDemo
{
    class CsharpInsensitiveReplaceExample
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        static void Main()
        {
            var response = ReplaceEx("this is a string", "is", "Is");
            Console.WriteLine(response);
        }

        /// <summary>
        /// Replaces the executable.
        /// </summary>
        /// <param name="original">The original.</param>
        /// <param name="pattern">The pattern.</param>
        /// <param name="replacement">The replacement.</param>
        /// <returns></returns>
        private static string ReplaceEx(string original,
                    string pattern, string replacement)
        {
            var position0 = 0;
        
            int position1;

            var count = 0; 
        
            var upperString = original.ToUpper();

            var upperPattern = pattern.ToUpper();

            var inc = (original.Length / pattern.Length) *
                      (replacement.Length - pattern.Length);

            var chars = new char[original.Length + Math.Max(0, inc)];

            while ((position1 = upperString.IndexOf(upperPattern, position0, StringComparison.Ordinal)) != -1)
            {
                for (var i = position0; i < position1; ++i)
                {
                    chars[count++] = original[i];
                }
                foreach (var t in replacement)
                {
                    chars[count++] = t;
                    position0 = position1 + pattern.Length;
                }
            }

            if (position0 == 0) return original;

            for (var i = position0; i < original.Length; ++i)
                chars[count++] = original[i];

            return new string(chars, 0, count);
        }
    }
}

Returns:

thIs Is a string