473,321 Members | 1,669 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,321 software developers and data experts.

Use switch with singleton objects

Why can't we use switches with singleton objects? I know that the compiler
cannot optimize them like constant values but the same is true for strings
and they are allowed in switches.

The reason is that I often use singleton classes as replacement for enum's
because enums does'nt provide me a (localizeable) names or descriptions when
I for example fill comboboxes with them.

Additionally I don't like that I can't put any code in the enum class
although I often have a lot of code that should be placed together with the
enum.
Maybe someaday .NET will provide an extensible and flexible enum class
feature like Java does.
Nov 16 '05 #1
10 1468
hi,

First of all you cannot mark a type as singleton, you make it behave as a
singleton in code. That is a concept that does not exist in the language.
Therefore it will behave as a regular object to the compiler.

Now, how you expect to give unique values to the case(s) ?

FRankly I don't understand why the need of the class being a singleton.
Could you further explain why this?
cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"cody" <de********@gmx.de> wrote in message
news:uX**************@tk2msftngp13.phx.gbl...
Why can't we use switches with singleton objects? I know that the compiler
cannot optimize them like constant values but the same is true for strings
and they are allowed in switches.

The reason is that I often use singleton classes as replacement for enum's
because enums does'nt provide me a (localizeable) names or descriptions
when
I for example fill comboboxes with them.

Additionally I don't like that I can't put any code in the enum class
although I often have a lot of code that should be placed together with
the
enum.
Maybe someaday .NET will provide an extensible and flexible enum class
feature like Java does.

Nov 16 '05 #2
cody wrote:
Why can't we use switches with singleton objects? I know that the compiler
cannot optimize them like constant values but the same is true for strings
and they are allowed in switches.
The compiler can't even see whether they are singletons.

Is there a problem with the below?

Type t = o.GetType();
if ( t == typeof(Singleton1) ) {
// do stuff;
else if ( o == typeof(Singleton2) )
// do stuff;
else
throw new ArgumentException(
string.Format("Unknown type: {0}", t), "o"));

The reason is that I often use singleton classes as replacement for enum's
because enums does'nt provide me a (localizeable) names or descriptions when
I for example fill comboboxes with them.


Uh, couldn't you use instances? Which would give you a similar "switch":

if ( o == singleton1 ) {
// do stuff;
else if ( o == singleton2 )
// do stuff;
else
throw new ArgumentException("Unknown object", "o");

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 16 '05 #3
Currently we are using the following scheme.
The Compiler can be sure that the values passed are really unique since we
assign
static readonly values at object creation time, I think the compiler should
be able
to recognize this pattern.

public class EkpSchema : EnumWrapper
{
public static readonly EkpSchema ImmerLetzter = new EkpSchema(0, "Immer
letzter Einkaufspreis");
public static readonly EkpSchema EkpNeu = new EkpSchema(1, "EKP Neu nach
Abverkauf");
public static readonly EkpSchema ImmerDurchschnitt = new EkpSchema(2, "Immer
durchschnittl. EKP");
public static readonly EkpSchema EkpManuell = new EkpSchema(3, "EKP
manuell");

EkpSchema(int id, string bez)
:base(id,bez)
{
}

public static EkpSchema GetByID(int val)
{
return (EkpSchema)EnumWrapper.GetByID(typeof(EkpSchema), val);
}

public static EkpSchema[] GetValues()
{
return (EkpSchema[])EnumWrapper.GetValues(typeof(EkpSchema));
}

}
Nov 16 '05 #4
Singleton doesn't neccesarily mean that we only have *one* singleton per
class, see my other post.

"Helge Jensen" <he**********@slog.dk> schrieb im Newsbeitrag
news:#c**************@TK2MSFTNGP10.phx.gbl...
cody wrote:
Why can't we use switches with singleton objects? I know that the compiler cannot optimize them like constant values but the same is true for strings and they are allowed in switches.


The compiler can't even see whether they are singletons.

Is there a problem with the below?

Type t = o.GetType();
if ( t == typeof(Singleton1) ) {
// do stuff;
else if ( o == typeof(Singleton2) )
// do stuff;
else
throw new ArgumentException(
string.Format("Unknown type: {0}", t), "o"));

The reason is that I often use singleton classes as replacement for enum's because enums does'nt provide me a (localizeable) names or descriptions when I for example fill comboboxes with them.


Uh, couldn't you use instances? Which would give you a similar "switch":

if ( o == singleton1 ) {
// do stuff;
else if ( o == singleton2 )
// do stuff;
else
throw new ArgumentException("Unknown object", "o");

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-

Nov 16 '05 #5
I hear you.

I spent quite some time on exactly the same issue myself. First, I tried to
implement something similar to Color/KnowColor pair in System.Drawing. i.e.:

enum KnownSex{Male, Female};

class Sex
{
public static readonly Male = new Sex(KnownSex.Male);
public static readonly Female = new Sex(KnownSex.Female);
...
public static Sex FromKnownSex(KnownSex sex)
{
switch (sex)
{
case KnownSex.Male:
return Sex.Male;
.....
}
}

[ And please, don't laugh at the notion of "unknown sex"! I live in
Thailand, I've seen strange things ;-) ]

The idea was to have object properties (like Person.Sex) to be set to enum
values, but use objects of Sex class in comboboxes etc. But... too much work
for too little. I settled down on using singletons. It just feel "more
right" than enums. And if/else if doesn't bother me at all. All my "enum
classes" have static field called List which returns all singleton objects
of this class, not just those defined in static fields like Male and Female
instances above. I've seen from your other posting that you're doing the
same with GetValues method; good, I might not be completely crazy.
Why can't we use switches with singleton objects? I know that the compiler
cannot optimize them like constant values but the same is true for strings
and they are allowed in switches.


I guess that you can use strings in switches because they are immutable.

As for localizing the enums, earlier today I posted some code which might
give you some food for thought. I'm repeating it below.

Alexander
---------------------------------------------------------

class FriendlyNameAttribute : Attribute
{
public readonly string Value;
public FriendlyNameAttribute(string value)
{
Value = value;
}
}

enum MyEnum {
[FriendlyName("Value of One")]
One,
[FriendlyName("Value of Two")]
Two,
Three
};

class MainClass
{
public static void Main(String[] args)
{
foreach (FieldInfo fi in typeof(MyEnum).GetFields())
{
FriendlyNameAttribute[] names =
(FriendlyNameAttribute[])fi.GetCustomAttributes(typeof(FriendlyNameAttribu te),
true);
if (names.Length > 0)
{
Console.WriteLine(names[0].Value);
}
else
{
Console.WriteLine(fi.Name);
}
}
}
}
Nov 16 '05 #6
comments inline.
I guess that you can use strings in switches because they are immutable.
My singletons also are but the compiler doesn't know that :)
As for localizing the enums, earlier today I posted some code which might
give you some food for thought. I'm repeating it below.

Alexander
---------------------------------------------------------

class FriendlyNameAttribute : Attribute
{
public readonly string Value;
public FriendlyNameAttribute(string value)
{
Value = value;
}
}

enum MyEnum {
[FriendlyName("Value of One")]
One,
[FriendlyName("Value of Two")]
Two,
Three
};

class MainClass
{
public static void Main(String[] args)
{
foreach (FieldInfo fi in typeof(MyEnum).GetFields())
{
FriendlyNameAttribute[] names =
(FriendlyNameAttribute[])fi.GetCustomAttributes(typeof(FriendlyNameAttribu te
), true);
if (names.Length > 0)
{
Console.WriteLine(names[0].Value);
}
else
{
Console.WriteLine(fi.Name);
}
}
}
}

This is a very great idea, it serves a friendyname which can be applied to
*any* type. It would also be extensible:

class FriendlyNameAttribute : Attribute
{
// ...

public static string GetFriedlyNameOf(Type t)
{
// get attribute here
}

public static string GetFriedlyNameOf(Enum e)
{
// get attribute here
}
}
Nov 16 '05 #7
cody <de********@gmx.de> wrote:
Singleton doesn't neccesarily mean that we only have *one* singleton per
class, see my other post.


In that case I think you're using the terminology in a way which is
different to what everyone else understands by "singleton". To me, a
singleton type is one which prevents the construction of more than one
instance of itself, and usually allows easy access to that one
instance.

What exactly do *you* mean by singleton?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
A class to which a fixed number ob instances exist and nobody can create
additionally instances.
The class has a private ctor and no factory methods but provides an
accesssor to each instance.

"Jon Skeet [C# MVP]" <sk***@pobox.com> schrieb im Newsbeitrag
news:MP***********************@msnews.microsoft.co m...
cody <de********@gmx.de> wrote:
Singleton doesn't neccesarily mean that we only have *one* singleton per
class, see my other post.


In that case I think you're using the terminology in a way which is
different to what everyone else understands by "singleton". To me, a
singleton type is one which prevents the construction of more than one
instance of itself, and usually allows easy access to that one
instance.

What exactly do *you* mean by singleton?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #9
cody <de********@gmx.de> wrote:
A class to which a fixed number ob instances exist and nobody can create
additionally instances. The class has a private ctor and no factory methods
but provides an accesssor to each instance.


Ah. That's similar to the normal meaning of singleton, but definitely
isn't the normal one. Sounds more like a flyweight to me. The "single"
part of "singleton" gives the clue that it only allows a *single*
instance.

In fact, your desired usage sounds quite like that of the enums which
are new to Java 1.5. What you could do is create a class which exposes
something like "EnumValue" as a property, and have an enum of the
actual values, which is used during construction. You could then switch
on that enum value.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10
Of course, if the only requirement was a single stack frame then you
could
just use static methods and fields.

http://www.geocities.com/jeff_louie/...on_pattern.htm

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
by: Uwe Mayer | last post by:
Hi, I've been looking into ways of creating singleton objects. With Python2.3 I usually used a module-level variable and a factory function to implement singleton objects. With Python2.4 I...
7
by: phl | last post by:
hello, My project in a web project. I choose to use singleton in one of my projects. Towards the end I realise that I seemed to have refered to the fields singleton in my other classes in my...
12
by: solex | last post by:
Hello, I am trying to model a session object that is essentially a collection of different items (connection string, user name, maps etc.) I would like this session object to be available to...
10
by: A_StClaire_ | last post by:
hi, I have a singleton Evaluation class that I'm calling repeatedly in one sequence. would someone plz have a look at the code below and tell me if one instance of the singleton can ever...
12
by: Preets | last post by:
Can anyone explain to me the exact use of private constructors in c++ ?
7
by: fredd00 | last post by:
Hi I'm just starting with singleton and would like to implement in my new web app. I have a question lets say i create a singleton DataHelper that holds a static SqlConnection object to...
3
weaknessforcats
by: weaknessforcats | last post by:
Design Pattern: The Singleton Overview Use the Singleton Design Pattern when you want to have only one instance of a class. This single instance must have a single global point of access. That...
2
by: Eric Lilja | last post by:
As the topic says, I wanted to make a re-usable singleton class that could create pointers to objects with non-trivial constructors. I came up with this: #ifndef SINGLETON_HPP #define...
3
by: stevewilliams2004 | last post by:
I am attempting to create a singleton, and was wondering if someone could give me a sanity check on the design - does it accomplish my constraints, and/or am I over complicating things. My design...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.