Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize static field in constructor. It's normal?

public class SharedCacheData : ISharedCacheData
{
    private readonly ISharedPetsService mPetsService;
    private static ISharedEmployeeService mSharedEmployeeService;
 public SharedCacheData(ISharedPetsService petsService, ISharedEmployeeService employeeService)
    {
        mPetsService = petsService;
        mSharedEmployeeService = employeeService;
    }

    public static string GetUserFullName(string key)
    {
        Hashtable value = HttpContext.Current.Application[USERFULLNAME_KEY] as Hashtable;
        if (value == null)
        {
            value = new Hashtable();
            HttpContext.Current.Application[USERFULLNAME_KEY] = value;
        }
        if (value.ContainsKey(key))
            return value[key] as string;

        string name = mSharedEmployeeService.FindOneUser(key);
        value[key] = name;
        return name;
    }

Whether initialize static field mSharedEmployeeService (service) in constructors?

like image 323
isxaker Avatar asked Feb 22 '11 13:02

isxaker


People also ask

Can a static field be initialized in a constructor?

You can define a static field using the static keyword. If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.

Can a normal class have static constructor?

A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded. A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.

Is it mandatory to initialize static variable?

Initialization of Instance variables But if you declare an instance variable static and final Java compiler will not initialize it in the default constructor therefore, it is mandatory to initialize static and final variables. If you don't a compile time error is generated.

Can you access static variable in constructor?

A static variable can be accessed without an object, therefore the variable shouldn't be static if you need to initialize in the constructor. It makes no sense to "initialize" a static member in a constructor. It will get reinitialized every time you create a new instance.


1 Answers

No, that's generally a bad idea. Every time you create a new instance, it will be replacing the static variable. That's almost certainly not what you want to do.

I wonder whether actually there should be two classes here - one for the pets service and one for the employee service. It's hard to tell from the code presented, but what we've got here really doesn't look like a good idea.

like image 112
Jon Skeet Avatar answered Oct 05 '22 04:10

Jon Skeet