TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Colin Basnett
NA
1
0
Singleton Troubles
Feb 21 2008 6:26 PM
I've used Singletons in Java, but I just can't seem to get it right with C#. I get a TypeInitializationException on the Checkers.Game class. Here's my code...
using System;
using System.Collections.Generic;
using System.Text;
namespace Checkers
{
class Program
{
public static void Main()
{
Game _Game = Game.Instance;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Checkers
{
public sealed class Game
{
private static Game _Instance = new Game();
private Board _Board = Board.Instance;
private Player[] _Players = new Player[2];
public static Game Instance
{
get
{
return _Instance;
}
}
public Board Board
{
get
{
return _Board;
}
set
{
_Board = value;
}
}
public Player[] Players
{
get
{
return _Players;
}
set
{
_Players = value;
}
}
private Game()
{
Players[0] = new Player(Player.Directions.Down);
Players[1] = new Player(Player.Directions.Up);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Checkers
{
public sealed class Board
{
private static Game _Game = Game.Instance;
private static Board _Instance = new Board();
private Piece[,] _Pieces = new Piece[8, 8];
public static Board Instance
{
get
{
return _Instance;
}
}
public Piece[,] Pieces
{
get
{
return _Pieces;
}
set
{
_Pieces = value;
}
}
private Board()
{
int X;
int Y;
for (X = 0; X < 8; X++)
{
for (Y = 0; Y < 2; Y++)
{
Pieces[X, Y] = new Piece(X, Y, _Game.Players[0]);
}
}
}
}
}
The exception I get is...
System.TypeInitializationException was unhandled
Message="The type initializer for 'Checkers.Game' threw an exception."
Source="Checkers"
TypeName="Checkers.Game"
StackTrace:
at Checkers.Game.get_Instance()
at Checkers.Program.Main() in C:\Documents and Settings\cbasnett\My Documents\Visual Studio 2005\Projects\Checkers\Checkers\Program.cs:line 11
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Reply
Answers (
1
)
form inheritance
Question about Inheritence in C#