473,799 Members | 3,224 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1489
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******** ******@tk2msftn gp13.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(Singleto n1) ) {
// do stuff;
else if ( o == typeof(Singleto n2) )
// do stuff;
else
throw new ArgumentExcepti on(
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 ArgumentExcepti on("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 ImmerDurchschni tt = 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)Enum Wrapper.GetByID (typeof(EkpSche ma), val);
}

public static EkpSchema[] GetValues()
{
return (EkpSchema[])EnumWrapper.Ge tValues(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**********@s log.dk> schrieb im Newsbeitrag
news:#c******** ******@TK2MSFTN GP10.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(Singleto n1) ) {
// do stuff;
else if ( o == typeof(Singleto n2) )
// do stuff;
else
throw new ArgumentExcepti on(
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 ArgumentExcepti on("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.Ma le);
public static readonly Female = new Sex(KnownSex.Fe male);
...
public static Sex FromKnownSex(Kn ownSex 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 FriendlyNameAtt ribute : Attribute
{
public readonly string Value;
public FriendlyNameAtt ribute(string value)
{
Value = value;
}
}

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

class MainClass
{
public static void Main(String[] args)
{
foreach (FieldInfo fi in typeof(MyEnum). GetFields())
{
FriendlyNameAtt ribute[] names =
(FriendlyNameAt tribute[])fi.GetCustomAt tributes(typeof (FriendlyNameAt tribute),
true);
if (names.Length > 0)
{
Console.WriteLi ne(names[0].Value);
}
else
{
Console.WriteLi ne(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 FriendlyNameAtt ribute : Attribute
{
public readonly string Value;
public FriendlyNameAtt ribute(string value)
{
Value = value;
}
}

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

class MainClass
{
public static void Main(String[] args)
{
foreach (FieldInfo fi in typeof(MyEnum). GetFields())
{
FriendlyNameAtt ribute[] names =
(FriendlyNameAt tribute[])fi.GetCustomAt tributes(typeof (FriendlyNameAt tribute
), true);
if (names.Length > 0)
{
Console.WriteLi ne(names[0].Value);
}
else
{
Console.WriteLi ne(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 FriendlyNameAtt ribute : Attribute
{
// ...

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

public static string GetFriedlyNameO f(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.co m>
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.co m> schrieb im Newsbeitrag
news:MP******** *************** @msnews.microso ft.com...
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.co m>
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.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10

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

Similar topics

26
2501
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 was looking into decorators. The examples from PEP 318 http://www.python.org/peps/pep-0318.html#examples don't work - AFAIK because:
7
2833
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 business logic a little precariously. I access my the fields in the singlton in my BLL classes directly. Is this a really bad violation of OOP rules? It's almost liek I have use the singlton as one big global variable. Is there any decent way of...
12
2455
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 other objects within my client application. I can do one of two things (1) make the session object a singleton (2) pass the session object to the methods that need them. Option 2 is a bit more complicated and messy then option 1. My other goal...
10
1484
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 "clash" with another? I'm asking because I'm getting unexpected results. I've looked for the problem the past several days and can't attribute the anomalies to logic errors.
12
8973
by: Preets | last post by:
Can anyone explain to me the exact use of private constructors in c++ ?
7
2240
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 share and on my page I do
3
18255
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 is, regardless of where the object is hidden, everyone needs access to it. The global point of access is the object's Instance() method. Individual users need to be prevented from creating their own instances of the Singleton.
2
1890
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 SINGLETON_HPP template<typename T> struct DefaultCreatorFunctor {
3
1807
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 constraints/environment are as follows: 1) Everything is single-threaded during static initialization (as in prior to the open brace of main) 2) The environment may be multi-threaded during nominal program execution (within {} of main) 3) I...
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9538
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10470
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10214
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9067
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6803
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5583
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4135
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3751
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.