Static Constructor C# with Example



Static Constructor C# with Example

 	using System;

	namespace CSharpClass{
		class RandomNumberClass
		{
			private static Random RandomKey; 	// Private static field
			
			static RandomNumberClass() 			// Static constructor
			{
				RandomKey = new Random(); 		// Initialize RandomKey
			}
			
			public int GetRandomNumber()
			{
				return RandomKey.Next();
			}
		}

		class UsingStaticConstructor
		{
			static void Main()
			{
				RandomNumberClass a = new RandomNumberClass();
				RandomNumberClass b = new RandomNumberClass();
				RandomNumberClass c = new RandomNumberClass();
				
				Console.WriteLine("Next Random #: {0}", a.GetRandomNumber());
				Console.WriteLine("Next Random #: {0}", b.GetRandomNumber());
				Console.WriteLine("Next Random #: {0}", c.GetRandomNumber());
			}
		}
	}
 

0 Comment's

Comment Form

Submit Comment