Wednesday, April 22, 2009

Mixin ins in c# or code extensions

 
    public interface IExtension
    {
    }
 
 
    public static class Extensions
    {
        public static string GetTypeInfo(this IExtension ext)
        {
            return String.Format("{0} {1}", ext.GetType().FullName, ext.GetHashCode().ToString());
        }
     
    }
    public static class Test
    {
        public static string GetTest(this IExtension debug)
        {
            return "Test string";
        }
    }
    class Program
    {
        static void Main()
        {
            var myObj = new MyClass();
            Console.WriteLine(myObj.GetTypeInfo());
            Console.WriteLine(myObj.GetTest());
            Console.Read();
        }
 
    }
    class MyClass : IExtension
    {
      
    }

C# does not support mixins ; mixins are like prewritten codes functions to be implemented by subclasses, it is different from interfaces interfaces are only signature does not contain functions mixins does. We can use code extensions to add extra functions to a class.It is pretty easy to use code extensions like above.

No comments: