Noxor
Noxor

Reputation: 61

Is it possible to have different value of static variable for every instance?

I have a class with some static variables and I want to create multiple independent instances of this class. Independent meaning, that they do not share values of these static variables.

Is there a way how to achieve this without refactoring said class?

Upvotes: 0

Views: 1125

Answers (2)

Tanzeel ur Rehman
Tanzeel ur Rehman

Reputation: 429

Static variables are shared among every instance of a type, so you need instance variables, that will solve your problem. so refactoring is needed.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500535

I have a class with some static variables and I want to create multiple independent instances of this class.

In that case you just don't want static variables. static means "associated with the type rather than an instance of the type" - you just want instance variables.

That may mean changes elsewhere in your app, of course, but there's nothing you can do about that - or at least, any alternatives are going to be much more hacky than just taking the straightforward approach.

Upvotes: 8

Related Questions