Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi All,
I am new to singleton class how to call the display method can u guide or send snippets


C#
public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
  public string display(string msg)
  {
     return "you have entered " + msg;
   }
}
Posted
Updated 20-Nov-13 21:51pm
v2

This singleton definition makes no sense. In particular, display makes no sense, incorrect (would work, but it needs to be static, because "this" is not used) and unrelated to singleton functionality. Exposing Instance would work but means bad style.

First, read this: http://en.wikipedia.org/wiki/Singleton_pattern[^].

And here is a good singleton sample: http://csharpindepth.com/Articles/General/Singleton.aspx[^].

—SA
 
Share this answer
 
Comments
lukeer 21-Nov-13 2:04am    
Despite your harsh comment on the op's code, it's exactly resembling the last example from your second link.

Since I have no experience with the Lazy<> type, is that example really that bad?
Sergey Alexandrovich Kryukov 21-Nov-13 14:19pm    
No, using Lazy is not a bad idea at all. The OP's sample does resemble right thing, but only resembles. I pointed out concrete problems. The sample lacks encapsulation, which practically makes it pointless. There is no a single step from using no Singleton pattern. Do you understand that the same behavior can be achieved without singleton, just by using one static object. And making a wrapping class around it only pays off when you add some useful encapsulation. And the problem with display is just a separate design bug. For example, FxCop rightfully detect non-static method not actually using "this" as a performance bug item.
—SA
Just try Singleton.display("input string")..

For singleton, you can consume as classname.methodname()..

does this help?
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 21-Nov-13 1:40am    
No, it won't even compile, with OP's Singleton definition. Should I even explain why?
Please, never give answers you did not even try to compile. Not answering is much better than confusing people with wrong answers.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900