Using Private Constructors - CSharp Custom Type

CSharp examples for Custom Type:Constructor

Introduction

To prevent an object from being created, create a private constructor.

Demo Code

using System;/*from   ww w.j  a  v  a 2  s  . c  o m*/
public class MyMath
{
   public static long Add( params int[] args )
   {
      int i = 0;
      long Answer = 0;
      for( i = 0; i < args.Length; i++)
      {
         Answer += args[i];
      }
      return Answer;
   }
   public static long Subtract( int arg1, int arg2 )
   {
      long Answer = 0;
      Answer = arg1 - arg2;
      return Answer;
   }
   private MyMath()
   {
      // nothing to do here since this will never get called!
   }
}
class MyApp
{
   public static void Main()
   {
      long Result = 0;
      // MyMath var = new MyMath();
      Result = MyMath.Add( 1, 2, 3 );
      Console.WriteLine("Add result is {0}", Result);
      Result = MyMath.Subtract( 5, 2 );
      Console.WriteLine("Subtract result is {0}", Result);
   }
}

Result


Related Tutorials