Translate

Sunday, July 28, 2013

C# difference between read only and constant

You might already know that the difference between readonly and constant is that readonly variables can be set in the constructor where as constants once declared cannot be changed.

But that is not the answer that you would expect from a technical person, the difference you read above is just a symptom. The real technical difference between constant and read only is that, the compiler replaces any reference to the constant by its actual value.

For example suppose I have a class Test that references another class Class1. If I am reading a contant value from class Class1 in class Test, then in the assembly of class Test, that reference will be replaced by its actual value.

This is the code for Class 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassLibrary1
{
    public class Class1
    {
        public const Decimal c = 25;
        public static readonly Decimal d = 40;

    }

}


This is the code for Test

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using ClassLibrary1;

namespace ConstReadOnlyDifference
{
    class Test
    {
       
        static void Main()
        {
            Console.WriteLine(Class1.c);
            Console.WriteLine(Class1.d);

        }
    }
}



Class 1 and Test are in seprate projects.




































If you compile the solution, equivalent of this is what actually goes into the assembly for ConsoleApplication3.


using ClassLibrary1;
using System;

namespace ConstReadOnlyDifference
{
  internal class Test
  {
    private static void Main()
    {
      Console.WriteLine(new Decimal(25));
      Console.WriteLine(Class1.d);
    }
  }
}


As you can see Class1.c is replaced by new Decimal(25)  Which means if you ever change the value of c in Class1, Class Test will still hold its previous value unless class Test is itself recompiled.


So never use constant for a value that will ever change in the future. 

Monday, July 22, 2013

Facts about Distributed Computing

When you build a distributed system, these are certain considerations that you should not forget to take into account.  These points were brought into attention by experts working on distributed computing worldwide.


  • The network is unreliable: For example there can be a physical breaking of a cable that carries the network traffic.
  • Latency is not zero:When you pass a reference to a large object to a method on a dll on the same machine, they are both share the same memory and hence there are no problems. But if you need to pass this to a web service, you need to serialize it and account for the time delay in sending a huge piece of data across.
  • Bandwidth is finite:  If you send very large data across network, it will lead to more lost TCP/IP packets. Hence more wasted bandwidth. In other words you would be paying for bandwidth that you didn't use.
  • The network is insecure
  • Topology changes with time: As an example the connections between machines can change over time, which is change to the topology.
  • There is more than one administrator: There are many networks and machines involved. Hence there will also be many administrators.
  • Transport cost is not zero: There could be a bandwidth cost for the amount of data being sent across
  • The network is hetrogeneous: For example different machines on the system might have different operating systems.

Sunday, July 21, 2013

Factory pattern tutorial c# (Simplified Version)

The need for factory pattern

In this example below based on the value of the paramater datasource we would need to decide which implementation of IDatasource to use. The problem with a code like this is that it does not adhere to the "closed for modification" design principle. If you add a new implementation of IDataSource called DataFromFile, then you will have to modify the code in the Main() and add a new else statement. Ideally, when you add a new implementation or switch implementation, you shouldn't have to modify code.

using System;

namespace LearnFactoryPattern
{
    class Test
    {
        static void Main()
        {
            var datasource = "SQL";

            IDataSource iData;

            if (datasource.Equals("SQL"))
            {
                iData = new DataFromSQL();
            }
            else if (datasource.Equals("XML"))
            {
                iData = new DataFromXML();
            }
            else
            {
                iData = null;
            }

            iData.GetData();//Displays Data from SQL


        }
    }

    public interface IDataSource
    {
        void GetData();

    }


    public class DataFromSQL : IDataSource
    {
        public void GetData()
        {
            Console.WriteLine("Data from SQL");
        }
    }


    public class DataFromXML : IDataSource
    {
        public void GetData()
        {
            Console.WriteLine("Data from XML");
        }
    }
  

}




To switch from DataFromSQL to DataFromXML, all I should have to do, should be to change a config setting. Factory pattern helps us achieve that.

Simple Factory Pattern

In this pattern we do not need to update the code if we want to switch implementations. All we do is make a change in the config file. These are the key things we need to do to make this happen.


  • Save the name of Implementation of IDatasource we want to use in the config file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
       <appSettings>
             <add key="DataSourceImplementationName" value="DataFromSQL" />
            
       </appSettings>
</configuration>




  • Load into a Dictionary, all the implementations of IDataSource that we have in the current assembly.
       Dictionary<string, Type> dataSources; 
      
        dataSources.Add(typeName, type);//types in the assembly that implement IDataSource
  • Get the name of implementation from the config file. Pass that class name into a method. That method looks up the dictionary dataSources for a type that matches the class name (type name) we just passed in. Then it creates an instance of that for us.
    public IDataSource CreateInstance(string dataSourceName)
    {
      ......

    }

The whole code that implements this is shown below. 

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;

namespace LearnFactoryPattern
{
    class Test
    {


        static void Main()
        {
            var dataSourceName = ConfigurationManager.AppSettings["DataSourceImplementationName"].ToLower();

            var factory = new DataSourceFactory();
            var dataSource=factory.CreateInstance(dataSourceName);
            dataSource.GetData();

        }
    }

    public interface IDataSource
    {
        void GetData();

    }


    public class DataFromSQL : IDataSource
    {
        public void GetData()
        {
            Console.WriteLine("Data from SQL");
        }
    }


    public class DataFromXML : IDataSource
    {
        public void GetData()
        {
            Console.WriteLine("Data from XML");
        }
    }

    /*******************************************************/
    /**************** FACTORY BELOW ************************/
    /*******************************************************/


    public class DataSourceFactory
    {
        Dictionary<string, Type> dataSources;

        public DataSourceFactory()
        {
            LoadDataSourceTypes();
        }

        public IDataSource CreateInstance(string dataSourceName)
        {

            var dataSourceImplementationName = GetTypeToCreate(dataSourceName);
            return (IDataSource)Activator.CreateInstance(dataSourceImplementationName);

        }

        public Type GetTypeToCreate(string dataSourceName)
        {
            return dataSources[dataSourceName];
        }

        public void LoadDataSourceTypes()
        {
            dataSources = new Dictionary<string, Type>();

            var typesinCurrentAssembly = Assembly.GetExecutingAssembly().GetTypes();//Get the interfaces and classes in the current assembly
            var interfaceName = typeof(IDataSource).ToString();//"IDataSource"

            foreach (var type in typesinCurrentAssembly)
            {

                if (type.GetInterface(interfaceName) != null)//Find the types that implement IDataSource
                {
                    var typeName = type.Name.ToLower();
                    dataSources.Add(typeName, type);
                }

            }

        }
    }

}


Its called factory pattern because, you pass the name of a class to a factory and it returns an instance of that class for you.




Friday, July 19, 2013

C# Programming Guidelines (C# programming best practices)

Scott Allen  in his plural sight video makes these 10 recommendations for writing quality software



  1. Keep classes small.
  2. Keep methods short. Ideally a method should sit on one screen. If its bigger than that, break it up into smaller methods.
  3. Except for API documentation comments (the one that goes on top of a method with ///) avoid comments. Good code with meaningful method names, is so readable and intention revealing that it does not need comments.
  4. Avoid multiple exit points (multiple returns) from a method. That is bad for code readability. Have just one exit at the bottom of the method.
  5. Encapsulate complex expressions.Instead of having an if condition with many checks, replace it with a method call. 
  6. Set up your project build warning level to 4 and set "Treat warnings as errors" to All.
  7. Avoid having more than 3 parameters to a method. If it needs 4 or more parameters, it should be one parameter which is an instance of a class that has those 4 parameters as properties.
  8. Avoid using boolean parameters to a method, because they reduce the code readability.
  9. Do not use exceptions for jumping around in the code.Use exceptions for errors only.
  10. Avoid using regions in code. According to Scott if your code is well organized using appropriately sized classes (a class that is NOT a swiss army knife) then you do not need regions.

C# Naming Guidelines (Naming standards c#)

The Microsoft recommended naming guidelines for C# can be found over here

You could also install a free open source tool called StyleCop , which integrates well with Visual studio and tells you where you have made naming mistakes.

Difference between override and new C#

The difference between override and new occurs when you cast a Child class into the Parent class.

When a child is cast into a parent and then you call a method on that instance, the child class method will be called only if it is an override.

using System;
 
namespace ConsoleApplication
{
 
    public class Test
    {
        public static void Main()
        {
            var chldA=new ChildA();
            var chldB = new ChildB();
 
            /*This is simple and straight forward*/
            Console.WriteLine(chldA.CallMe());// prints ChildA
            Console.WriteLine(chldB.CallMe());// prints ChildB
 
 
            /*Cast child into the parent*/
            var p1 = (Parent)chldA;
            var p2 = (Parent)chldB;
 
           
            /*This is where the subtle difference is*/
            Console.WriteLine(p1.CallMe());// prints Parent
            Console.WriteLine(p2.CallMe());// prints ChildB
        }
    }
 
    public class Parent
    {
        public virtual string CallMe()
        {
            return "Parent";
        }
    }
 
    public class ChildA : Parent
    {
        public new string CallMe()//new
        {
            return "ChildA";
        }
    }
 
    public class ChildB : Parent
    {
        public override string CallMe()//override
        {
            return "ChildB";
        }
    }
 
}

Saturday, July 6, 2013

Difference between ref and out c#

ref means value must be assigned before going in the method. out means value must be assigned before going out of the method.

For example, the code below will fail if we pass x into the method as out instead of ref.


using System;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            int p=0;
            Test(ref p);

        }

        static void Test(ref int x)
        {
        //if x is passed in as out, compilation will fail with an error
        //"The out parameter 'x' must be assigned to before control leaves the current   method"    

        }

    }
}




This code below will fail if we pass x in as ref instead of out. 

using System;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            int p;// NOTE: We have not initialized p here (No value before going in.)
            Test(out p);

        }

        static void Test(out int x)
        {
            //if x is passed in as ref, compilation will fail with an error
            //"Use of unassigned local variable 'p' "

            x = 5;
        }

    }
}

Friday, July 5, 2013

get size of a type c# (How to find size of a class in memory c#)

Use System.Runtime.InteropServices.Marshal.SizeOf(Type t) to find the size of a type. See below for an example.

In project properties under build set Allow unsafe code










The code below uses the method Marshal.SizeOf() to find the size of the class Point

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {

            unsafe
            {
                var sizeinBytes = Marshal.SizeOf(typeof(Point));//size in bytes
                Console.WriteLine(sizeinBytes);//16
            }


        }


        [StructLayout(LayoutKind.Sequential)]
        public class Point
        {
            int x;//4 bytes
            int y;//4 bytes
            private int[] i = new int[10];//reference to an array will hold a 32 bit address (for a 32 bit address bus), which is 4 bytes
            AnyClass ac;//reference to a class will hold a 32 bit address (for a 32 bit address bus), which is 4 bytes
        }

        public class AnyClass
        {

        }

    }
}



Thursday, July 4, 2013

c# float vs double vs decimal

Decimal calculations have a higher precision but are 10 times slower than double calculations. Decimal is used for financial calculations.


Float
Double
Decimal
Set x=1
var x=1f;
var x=1d;
var x=1m;
Storage
32 bits
64 bits
128 bits
Range
-1038 to 1038
-10308 to 10308
-1028 to 1028
Smallest number
10-45
10-324
10-28
Significant figures
8
16
29


using System;

namespace ConsoleApplication3
{
  class Program
  {
    static void Main(string[] args)
    {
      float   f = 1f / 6f;
      double  d = 1d / 6d;
      decimal m = 1M / 6M;

      Console.WriteLine(f);//0.1666667                       
      Console.WriteLine(d);//0.166666666666667              
      Console.WriteLine(m);//0.1666666666666666666666666667                 
    }
  }
}


c# check divide by zero

In C# if the type is float or double, divide by zero does NOT throw an exception. Dividing by zero results in Infinity (positive or negative) Or Not a Number.

using System;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            var k = 1f / 0f;
            Console.WriteLine(k);// Displays Infinity
            if(float.IsPositiveInfinity(k))
            {
                Console.WriteLine("Positive infinity");//code enters here
            }

            var z = 0f / 0f;
            Console.WriteLine(z);//Displays NaN
            if(float.IsNaN(z))
            {
                Console.WriteLine("Not a Number");//code enters here
            }

        }
    }
}