I have following
namespace Mine.Bits
{
public
static class Bits{
static class Bits { static UInt64[] BitMasks;
static Bits(){
UInt64 BitMask(int i) { return BitMasks[i]}
}
In another file I specify
using Mine.Bits;
but despite that I have to use
UInt64 CurrentMask = Mine.Bits.Bits.BitMask(3);
instead of just BitMask(3)
As I'm new to C# I would like to know what i do wrong and how I should achieve my goal.
Also operator overloading to GET BitMasks[i] would be nice (of course checking on bounds)
JackPosted Jan 9, 2008, 9:22 AM
Thanks for useful reply.
Indeed I intended to create a singleton of that class and had a look at http://www.yoda.arachsys.com/csharp/singleton.html how to do it well already.
AlanPosted Jan 9, 2008, 6:36 AM
When you insert the line:
using Mine.Bits;
into a source file, then you can use any type (class, struct, enum etc) defined in the Mine.Bits namespace without fully qualifying its name. However, you can't use any static members of those types (properties, methods, fields etc) unless you qualify them with the type name.
So, Bits.BitMask(3) should be OK but BitMask(3) is not allowed.
Incidentally, you seem to have a problem with your static class, Bits, in that another static class, also called Bits, is nested inside it! To get it to compile and to expose the BitMask() method to outside code, I'd have thought you'd need:
namespace Mine.Bits
{
public static class Bits
{
static UInt64[] BitMasks;
static Bits()
{
//
}
public static UInt64 BitMask(int i) { return BitMasks[i];}
}
}
As things stand, it's not possible to use operator overloading because the [] operator can't be overloaded. Nor are static indexers supported.
However, if you changed Bits to a singleton rather than a static class, then you would be able to define an indexer on it:
public sealed class Bits
{
static Bits instance = null;
static readonly object padlock = new object(); // simple thread locking
UInt64[] BitMasks = new UInt64[]{1,2};
// private constructor
Bits()
{
//
}
public static Bits Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Bits();
}
return instance;
}
}
}
public UInt64 this[int index]
{
get
{
if (index >= 0 && index < BitMasks.Length)
{
return BitMasks[index];
}
else
{
return 0; // say
}
}
}
}
You could then call the indexer with code like this:
Bits bits = Bits.Instance;
UInt64 CurrentMask = bits[3];