Search code examples
oopclassc#-4.0staticnon-static

A Beginner Puzzle of Static and Non-Static Classes in OOP ( C# )


A friend of mine (from work) asked me a question.

  1. Remove the static keyword from the Dictionary Live from the Members class.
  2. Don't use new Members(); to create an instance in Check(...) method.

So with these rules, what you have to do for call Live from other class like:

Members.Live.TryGetValue(signatureFromRequest, out userId);

I have this;

using System;
using System.Collections.Generic;
namespace Webbing.Session
{
    public class Members
    {
        // THAT Dictionary Live was a static... public static Dictionary...
        public Dictionary Guid, int> Live = new Dictionary Guid,int>();
    }
}

and this:

using System;
using WcfService.Session;

namespace Webbing.BusinessDb
{
    public class Signature
    {
        public static bool Check(Guid signatureFromRequest)
        {
            bool result = false;

            int userId;

            Members checker = new Members(); // <--------- don't use this
            checker.Live.TryGetValue(signatureFromRequest, out userId);

            if (userId != 0)
            {
                result = true;
            }

            return result;
        }
    }
}

He is saying, "there is way to do it.", but I can't find it and I don't believe there actually is. What is your opinion?

UPDATE/ANSWER: I solved the question with Daniel Hilgarth 's help... Here it is;


using System;
using System.Collections.Generic;

namespace Webbing.Session { public class Members { // Guid, userId public Dictionary Guid, int> Live = new Dictionary Guid,int>();

    private static readonly Members __instance = new Members();

    public static Members Instance
    {
        get
        {
            return __instance;
        }
    }
}

}

Usage: Members.Instance.Live.TryGetValue(signatureFromRequest, out userId);


Solution

  • There is no way with the exact syntax you provided.
    One possibility would be a singleton, but it would look like this:

    Members.Instance.Live.TryGetValue(signatureFromRequest, out userId);
    

    Note the .Instance part.

    See here for several ways to implement a singleton.

    As you can see, now the Live property isn't static anymore but the new property Instance is...

    I guess it will be best to simply ask your colleague what he meant.