C#: Protected Variables inside of a Generic Class can be accessed by a different subclass of that Generic...
Say I have a generic class Foo, that has a variable that is protected
public class Foo<T>
{
protected bool knowsFu;
}
I also have 2 sub-classes: Bar and Pipe
public class Bar : Foo<Bar> {}
public class Pipe : Foo<Pipe> {}
It is actually possible for me to access the knowsFu in Pipe FROM Bar, e.g.:
public class Bar : Foo<Bar>
{
void UpdateFuInOtherClass(Pipe p)
{
p.knowsFu = false;
}
}
Is this intended behaviour? (If so, what would be the usecase?)
Is there a way for me to prevent other Foo-Subclasses from modifying/reaching the protected variable inside of my current subclass?
More specifically: I'm using a generic class to implement the Singleton-Pattern:
https://en.wikipedia.org/wiki/Singleton_pattern
However, I'm currently able to access any singleton's protected instance-variable, as long as I am inside of another Singleton. Is there a way to prevent this?
EDIT: It might be relevant to note that the protected variable (knowsFu) is actually STATIC as well.
EDIT2: Ok, maybe the example was abit too generic.. here's how I'm actually currently implementing it:
why use Singleton? A:The platform I'm working on is Unity3D, in which the pattern is used frequently
I have a generically typed abstract class SingletonBehaviour
public abstract class SingletonBehaviour<T> where T : MonoBehaviour
{
public static T Instance { get { return instance; } }
protected static T instance { get; private set; } }
// Loading is done through Unitys Awake-Method
}
One of the Singleton-Objects that I'm using is the APIManager
public class APIManager : SingletonBehaviour<APIManager>
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
However, since most of my projects need some better API-implementation than that, what I'm currently doing is:
public class ProjectAAPIManager : APIManager
{
// Overriding Instance so my return value is not APIManager but instead ProjectAAPIManager
public static new ProjectAAPIMamager Instance { get { return (ProjectAAPIManager)instance; } }
}
This ^ is the reason my (inner) instance-variable is protected, and not private.
However, because of this, any other SingletonBehaviour in my project can now access the (inner) instance-variable on my ProjectAAPIManager
public class GameController : SingletonBehaviour<GameController>
{
private void AMethod()
{
// Accessing inner variable instead of public one
ProjectAAPIManager.instance.DoSomething();
}
}
As it's only the getter, this currently does not really matter. But what if I'd need access to the setter in my subclass as well?
Also: would it be worth it to generically type my APIManager as well?
c# generics singleton generic-programming
add a comment |
Say I have a generic class Foo, that has a variable that is protected
public class Foo<T>
{
protected bool knowsFu;
}
I also have 2 sub-classes: Bar and Pipe
public class Bar : Foo<Bar> {}
public class Pipe : Foo<Pipe> {}
It is actually possible for me to access the knowsFu in Pipe FROM Bar, e.g.:
public class Bar : Foo<Bar>
{
void UpdateFuInOtherClass(Pipe p)
{
p.knowsFu = false;
}
}
Is this intended behaviour? (If so, what would be the usecase?)
Is there a way for me to prevent other Foo-Subclasses from modifying/reaching the protected variable inside of my current subclass?
More specifically: I'm using a generic class to implement the Singleton-Pattern:
https://en.wikipedia.org/wiki/Singleton_pattern
However, I'm currently able to access any singleton's protected instance-variable, as long as I am inside of another Singleton. Is there a way to prevent this?
EDIT: It might be relevant to note that the protected variable (knowsFu) is actually STATIC as well.
EDIT2: Ok, maybe the example was abit too generic.. here's how I'm actually currently implementing it:
why use Singleton? A:The platform I'm working on is Unity3D, in which the pattern is used frequently
I have a generically typed abstract class SingletonBehaviour
public abstract class SingletonBehaviour<T> where T : MonoBehaviour
{
public static T Instance { get { return instance; } }
protected static T instance { get; private set; } }
// Loading is done through Unitys Awake-Method
}
One of the Singleton-Objects that I'm using is the APIManager
public class APIManager : SingletonBehaviour<APIManager>
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
However, since most of my projects need some better API-implementation than that, what I'm currently doing is:
public class ProjectAAPIManager : APIManager
{
// Overriding Instance so my return value is not APIManager but instead ProjectAAPIManager
public static new ProjectAAPIMamager Instance { get { return (ProjectAAPIManager)instance; } }
}
This ^ is the reason my (inner) instance-variable is protected, and not private.
However, because of this, any other SingletonBehaviour in my project can now access the (inner) instance-variable on my ProjectAAPIManager
public class GameController : SingletonBehaviour<GameController>
{
private void AMethod()
{
// Accessing inner variable instead of public one
ProjectAAPIManager.instance.DoSomething();
}
}
As it's only the getter, this currently does not really matter. But what if I'd need access to the setter in my subclass as well?
Also: would it be worth it to generically type my APIManager as well?
c# generics singleton generic-programming
protected bool knowsFu { get; private set; }
?
– stuartd
Nov 22 at 17:35
Yeah.. That's what I'm using now.. However, what if I need a protected (inner) set as well?
– Frank v Hoof
Nov 22 at 17:48
"A protected member is accessible within its class and by derived class instances."
– stuartd
Nov 22 at 17:52
add a comment |
Say I have a generic class Foo, that has a variable that is protected
public class Foo<T>
{
protected bool knowsFu;
}
I also have 2 sub-classes: Bar and Pipe
public class Bar : Foo<Bar> {}
public class Pipe : Foo<Pipe> {}
It is actually possible for me to access the knowsFu in Pipe FROM Bar, e.g.:
public class Bar : Foo<Bar>
{
void UpdateFuInOtherClass(Pipe p)
{
p.knowsFu = false;
}
}
Is this intended behaviour? (If so, what would be the usecase?)
Is there a way for me to prevent other Foo-Subclasses from modifying/reaching the protected variable inside of my current subclass?
More specifically: I'm using a generic class to implement the Singleton-Pattern:
https://en.wikipedia.org/wiki/Singleton_pattern
However, I'm currently able to access any singleton's protected instance-variable, as long as I am inside of another Singleton. Is there a way to prevent this?
EDIT: It might be relevant to note that the protected variable (knowsFu) is actually STATIC as well.
EDIT2: Ok, maybe the example was abit too generic.. here's how I'm actually currently implementing it:
why use Singleton? A:The platform I'm working on is Unity3D, in which the pattern is used frequently
I have a generically typed abstract class SingletonBehaviour
public abstract class SingletonBehaviour<T> where T : MonoBehaviour
{
public static T Instance { get { return instance; } }
protected static T instance { get; private set; } }
// Loading is done through Unitys Awake-Method
}
One of the Singleton-Objects that I'm using is the APIManager
public class APIManager : SingletonBehaviour<APIManager>
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
However, since most of my projects need some better API-implementation than that, what I'm currently doing is:
public class ProjectAAPIManager : APIManager
{
// Overriding Instance so my return value is not APIManager but instead ProjectAAPIManager
public static new ProjectAAPIMamager Instance { get { return (ProjectAAPIManager)instance; } }
}
This ^ is the reason my (inner) instance-variable is protected, and not private.
However, because of this, any other SingletonBehaviour in my project can now access the (inner) instance-variable on my ProjectAAPIManager
public class GameController : SingletonBehaviour<GameController>
{
private void AMethod()
{
// Accessing inner variable instead of public one
ProjectAAPIManager.instance.DoSomething();
}
}
As it's only the getter, this currently does not really matter. But what if I'd need access to the setter in my subclass as well?
Also: would it be worth it to generically type my APIManager as well?
c# generics singleton generic-programming
Say I have a generic class Foo, that has a variable that is protected
public class Foo<T>
{
protected bool knowsFu;
}
I also have 2 sub-classes: Bar and Pipe
public class Bar : Foo<Bar> {}
public class Pipe : Foo<Pipe> {}
It is actually possible for me to access the knowsFu in Pipe FROM Bar, e.g.:
public class Bar : Foo<Bar>
{
void UpdateFuInOtherClass(Pipe p)
{
p.knowsFu = false;
}
}
Is this intended behaviour? (If so, what would be the usecase?)
Is there a way for me to prevent other Foo-Subclasses from modifying/reaching the protected variable inside of my current subclass?
More specifically: I'm using a generic class to implement the Singleton-Pattern:
https://en.wikipedia.org/wiki/Singleton_pattern
However, I'm currently able to access any singleton's protected instance-variable, as long as I am inside of another Singleton. Is there a way to prevent this?
EDIT: It might be relevant to note that the protected variable (knowsFu) is actually STATIC as well.
EDIT2: Ok, maybe the example was abit too generic.. here's how I'm actually currently implementing it:
why use Singleton? A:The platform I'm working on is Unity3D, in which the pattern is used frequently
I have a generically typed abstract class SingletonBehaviour
public abstract class SingletonBehaviour<T> where T : MonoBehaviour
{
public static T Instance { get { return instance; } }
protected static T instance { get; private set; } }
// Loading is done through Unitys Awake-Method
}
One of the Singleton-Objects that I'm using is the APIManager
public class APIManager : SingletonBehaviour<APIManager>
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
However, since most of my projects need some better API-implementation than that, what I'm currently doing is:
public class ProjectAAPIManager : APIManager
{
// Overriding Instance so my return value is not APIManager but instead ProjectAAPIManager
public static new ProjectAAPIMamager Instance { get { return (ProjectAAPIManager)instance; } }
}
This ^ is the reason my (inner) instance-variable is protected, and not private.
However, because of this, any other SingletonBehaviour in my project can now access the (inner) instance-variable on my ProjectAAPIManager
public class GameController : SingletonBehaviour<GameController>
{
private void AMethod()
{
// Accessing inner variable instead of public one
ProjectAAPIManager.instance.DoSomething();
}
}
As it's only the getter, this currently does not really matter. But what if I'd need access to the setter in my subclass as well?
Also: would it be worth it to generically type my APIManager as well?
c# generics singleton generic-programming
c# generics singleton generic-programming
edited Nov 22 at 19:03
asked Nov 22 at 17:30
Frank v Hoof
207
207
protected bool knowsFu { get; private set; }
?
– stuartd
Nov 22 at 17:35
Yeah.. That's what I'm using now.. However, what if I need a protected (inner) set as well?
– Frank v Hoof
Nov 22 at 17:48
"A protected member is accessible within its class and by derived class instances."
– stuartd
Nov 22 at 17:52
add a comment |
protected bool knowsFu { get; private set; }
?
– stuartd
Nov 22 at 17:35
Yeah.. That's what I'm using now.. However, what if I need a protected (inner) set as well?
– Frank v Hoof
Nov 22 at 17:48
"A protected member is accessible within its class and by derived class instances."
– stuartd
Nov 22 at 17:52
protected bool knowsFu { get; private set; }
?– stuartd
Nov 22 at 17:35
protected bool knowsFu { get; private set; }
?– stuartd
Nov 22 at 17:35
Yeah.. That's what I'm using now.. However, what if I need a protected (inner) set as well?
– Frank v Hoof
Nov 22 at 17:48
Yeah.. That's what I'm using now.. However, what if I need a protected (inner) set as well?
– Frank v Hoof
Nov 22 at 17:48
"A protected member is accessible within its class and by derived class instances."
– stuartd
Nov 22 at 17:52
"A protected member is accessible within its class and by derived class instances."
– stuartd
Nov 22 at 17:52
add a comment |
2 Answers
2
active
oldest
votes
Your question is nothing short of bewildering. How can you make a protected member not be accesible from a derived class? Well, a good start is not making it protected.
protected
is by definition exactly what you don't want, so don't use it! Use private instead.
If what you are asking is how to make it a readonly member when accessed from derived types, you have two options:
- Declare it as readonly in the base class if possible.
- Use a protected property instead with a private setter.
Many novice coders seems to think protected members aren't part of the public surface of the type but they really are, as long as the class can be extended. As such, the rules of public members apply: never expose public fields unless they are readonly or constants, use properties instead.
1. Can't. Since I'm using Unity3D, Initialization is done in the Awake()-method, as there is no Constructor.
– Frank v Hoof
Nov 22 at 19:09
2. (Won't let me newline for some reason): That is my current solution. However, what if my subclass would need set-access as well?
– Frank v Hoof
Nov 22 at 19:10
@FrankvHoof Then make the setter protected too...
– InBetween
Nov 22 at 19:17
That would make it accessible from ANY of my singletons though, not the subclass itself only.
– Frank v Hoof
Nov 22 at 19:20
@FrankvHoof Yes, but the fact that you want derived types to access different members seems like a pretty bad code smell unless the distinction is between classes you or your team are implementing (same assembly) and future public consumers. In that case you can use theprivate protected
access modifier (you need C# 7.2).
– InBetween
Nov 22 at 19:24
|
show 3 more comments
You should not have classes that implement your generic singleton class.
Otherwise, by default, your protected fields will be accessible by the subclasses (it's what "protected" keyword does)
Instead, you should do something like this:
class Program
{
static void Main(string args)
{
var barInstance = Foo<Bar>.GetInstance();
}
}
public class Foo<T> where T : new()
{
protected bool knowsFu;
private static T _instance;
public static T GetInstance()
{
if (_instance == null)
_instance = new T();
return _instance;
}
}
public class Bar
{
public Bar()
{
}
}
Edit 1:
To use a singleton, you should not make another class implement the singleton behavior (This is not how the singleton pattern works).
To use the same classes as your second example, you should do something like this.
public class SingletonBehaviour<T> where T : new()
{
public static T Instance
{
get
{
if(instance == null)
instance = new T()
return instance;
}
}
private static T instance { get; set; }
}
public class APIManager // This class should not inherit from the SingletonBehavior class
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
public class ProjectAAPIManager : APIManager
{
public ProjectAAPIManager GetInstance() => SingletonBehavior<ProjectAAPIManager>.Instance();
}
the knowsFu is actually the _instance in my case.. I have a 'generic' API-manager, that has things like my accesskey, HTTPPost-methods, etc. This class inherits my Singleton-GenericClass public class APIManager : SingletonBehaviour<APIManager>{} However, this functionality is used in multiple of my projects. I thus have a public class ProjectAAPIManager : APIManager {} This means that the public Instance-variable in ProjectAAPIManager is actually of type APIManager, not ProjectAAPIManager. The way I'm currently handling this is with a public new PAAPIM Instance { return (PAAPIM)_inst}
– Frank v Hoof
Nov 22 at 18:07
I updated my answer with your examples. I think the problem is your usage of the singleton class. In a singleton, your instance should be private. You should only have a public property that will return your instance if it exists, or create a new one if it doesn't. Hope this helps!
– slig_3
Nov 22 at 20:30
Inheriting from Singleton is the recommended/advised implementation here, as Unity-Objects (scripts) do not have constructors. They are usually created through a call to AddComponent<ClassType>(). See wiki.unity3d.com/index.php/Singleton
– Frank v Hoof
Nov 22 at 21:44
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53435884%2fc-protected-variables-inside-of-a-generic-class-can-be-accessed-by-a-different%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Your question is nothing short of bewildering. How can you make a protected member not be accesible from a derived class? Well, a good start is not making it protected.
protected
is by definition exactly what you don't want, so don't use it! Use private instead.
If what you are asking is how to make it a readonly member when accessed from derived types, you have two options:
- Declare it as readonly in the base class if possible.
- Use a protected property instead with a private setter.
Many novice coders seems to think protected members aren't part of the public surface of the type but they really are, as long as the class can be extended. As such, the rules of public members apply: never expose public fields unless they are readonly or constants, use properties instead.
1. Can't. Since I'm using Unity3D, Initialization is done in the Awake()-method, as there is no Constructor.
– Frank v Hoof
Nov 22 at 19:09
2. (Won't let me newline for some reason): That is my current solution. However, what if my subclass would need set-access as well?
– Frank v Hoof
Nov 22 at 19:10
@FrankvHoof Then make the setter protected too...
– InBetween
Nov 22 at 19:17
That would make it accessible from ANY of my singletons though, not the subclass itself only.
– Frank v Hoof
Nov 22 at 19:20
@FrankvHoof Yes, but the fact that you want derived types to access different members seems like a pretty bad code smell unless the distinction is between classes you or your team are implementing (same assembly) and future public consumers. In that case you can use theprivate protected
access modifier (you need C# 7.2).
– InBetween
Nov 22 at 19:24
|
show 3 more comments
Your question is nothing short of bewildering. How can you make a protected member not be accesible from a derived class? Well, a good start is not making it protected.
protected
is by definition exactly what you don't want, so don't use it! Use private instead.
If what you are asking is how to make it a readonly member when accessed from derived types, you have two options:
- Declare it as readonly in the base class if possible.
- Use a protected property instead with a private setter.
Many novice coders seems to think protected members aren't part of the public surface of the type but they really are, as long as the class can be extended. As such, the rules of public members apply: never expose public fields unless they are readonly or constants, use properties instead.
1. Can't. Since I'm using Unity3D, Initialization is done in the Awake()-method, as there is no Constructor.
– Frank v Hoof
Nov 22 at 19:09
2. (Won't let me newline for some reason): That is my current solution. However, what if my subclass would need set-access as well?
– Frank v Hoof
Nov 22 at 19:10
@FrankvHoof Then make the setter protected too...
– InBetween
Nov 22 at 19:17
That would make it accessible from ANY of my singletons though, not the subclass itself only.
– Frank v Hoof
Nov 22 at 19:20
@FrankvHoof Yes, but the fact that you want derived types to access different members seems like a pretty bad code smell unless the distinction is between classes you or your team are implementing (same assembly) and future public consumers. In that case you can use theprivate protected
access modifier (you need C# 7.2).
– InBetween
Nov 22 at 19:24
|
show 3 more comments
Your question is nothing short of bewildering. How can you make a protected member not be accesible from a derived class? Well, a good start is not making it protected.
protected
is by definition exactly what you don't want, so don't use it! Use private instead.
If what you are asking is how to make it a readonly member when accessed from derived types, you have two options:
- Declare it as readonly in the base class if possible.
- Use a protected property instead with a private setter.
Many novice coders seems to think protected members aren't part of the public surface of the type but they really are, as long as the class can be extended. As such, the rules of public members apply: never expose public fields unless they are readonly or constants, use properties instead.
Your question is nothing short of bewildering. How can you make a protected member not be accesible from a derived class? Well, a good start is not making it protected.
protected
is by definition exactly what you don't want, so don't use it! Use private instead.
If what you are asking is how to make it a readonly member when accessed from derived types, you have two options:
- Declare it as readonly in the base class if possible.
- Use a protected property instead with a private setter.
Many novice coders seems to think protected members aren't part of the public surface of the type but they really are, as long as the class can be extended. As such, the rules of public members apply: never expose public fields unless they are readonly or constants, use properties instead.
edited Nov 22 at 18:17
answered Nov 22 at 18:10
InBetween
25k33967
25k33967
1. Can't. Since I'm using Unity3D, Initialization is done in the Awake()-method, as there is no Constructor.
– Frank v Hoof
Nov 22 at 19:09
2. (Won't let me newline for some reason): That is my current solution. However, what if my subclass would need set-access as well?
– Frank v Hoof
Nov 22 at 19:10
@FrankvHoof Then make the setter protected too...
– InBetween
Nov 22 at 19:17
That would make it accessible from ANY of my singletons though, not the subclass itself only.
– Frank v Hoof
Nov 22 at 19:20
@FrankvHoof Yes, but the fact that you want derived types to access different members seems like a pretty bad code smell unless the distinction is between classes you or your team are implementing (same assembly) and future public consumers. In that case you can use theprivate protected
access modifier (you need C# 7.2).
– InBetween
Nov 22 at 19:24
|
show 3 more comments
1. Can't. Since I'm using Unity3D, Initialization is done in the Awake()-method, as there is no Constructor.
– Frank v Hoof
Nov 22 at 19:09
2. (Won't let me newline for some reason): That is my current solution. However, what if my subclass would need set-access as well?
– Frank v Hoof
Nov 22 at 19:10
@FrankvHoof Then make the setter protected too...
– InBetween
Nov 22 at 19:17
That would make it accessible from ANY of my singletons though, not the subclass itself only.
– Frank v Hoof
Nov 22 at 19:20
@FrankvHoof Yes, but the fact that you want derived types to access different members seems like a pretty bad code smell unless the distinction is between classes you or your team are implementing (same assembly) and future public consumers. In that case you can use theprivate protected
access modifier (you need C# 7.2).
– InBetween
Nov 22 at 19:24
1. Can't. Since I'm using Unity3D, Initialization is done in the Awake()-method, as there is no Constructor.
– Frank v Hoof
Nov 22 at 19:09
1. Can't. Since I'm using Unity3D, Initialization is done in the Awake()-method, as there is no Constructor.
– Frank v Hoof
Nov 22 at 19:09
2. (Won't let me newline for some reason): That is my current solution. However, what if my subclass would need set-access as well?
– Frank v Hoof
Nov 22 at 19:10
2. (Won't let me newline for some reason): That is my current solution. However, what if my subclass would need set-access as well?
– Frank v Hoof
Nov 22 at 19:10
@FrankvHoof Then make the setter protected too...
– InBetween
Nov 22 at 19:17
@FrankvHoof Then make the setter protected too...
– InBetween
Nov 22 at 19:17
That would make it accessible from ANY of my singletons though, not the subclass itself only.
– Frank v Hoof
Nov 22 at 19:20
That would make it accessible from ANY of my singletons though, not the subclass itself only.
– Frank v Hoof
Nov 22 at 19:20
@FrankvHoof Yes, but the fact that you want derived types to access different members seems like a pretty bad code smell unless the distinction is between classes you or your team are implementing (same assembly) and future public consumers. In that case you can use the
private protected
access modifier (you need C# 7.2).– InBetween
Nov 22 at 19:24
@FrankvHoof Yes, but the fact that you want derived types to access different members seems like a pretty bad code smell unless the distinction is between classes you or your team are implementing (same assembly) and future public consumers. In that case you can use the
private protected
access modifier (you need C# 7.2).– InBetween
Nov 22 at 19:24
|
show 3 more comments
You should not have classes that implement your generic singleton class.
Otherwise, by default, your protected fields will be accessible by the subclasses (it's what "protected" keyword does)
Instead, you should do something like this:
class Program
{
static void Main(string args)
{
var barInstance = Foo<Bar>.GetInstance();
}
}
public class Foo<T> where T : new()
{
protected bool knowsFu;
private static T _instance;
public static T GetInstance()
{
if (_instance == null)
_instance = new T();
return _instance;
}
}
public class Bar
{
public Bar()
{
}
}
Edit 1:
To use a singleton, you should not make another class implement the singleton behavior (This is not how the singleton pattern works).
To use the same classes as your second example, you should do something like this.
public class SingletonBehaviour<T> where T : new()
{
public static T Instance
{
get
{
if(instance == null)
instance = new T()
return instance;
}
}
private static T instance { get; set; }
}
public class APIManager // This class should not inherit from the SingletonBehavior class
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
public class ProjectAAPIManager : APIManager
{
public ProjectAAPIManager GetInstance() => SingletonBehavior<ProjectAAPIManager>.Instance();
}
the knowsFu is actually the _instance in my case.. I have a 'generic' API-manager, that has things like my accesskey, HTTPPost-methods, etc. This class inherits my Singleton-GenericClass public class APIManager : SingletonBehaviour<APIManager>{} However, this functionality is used in multiple of my projects. I thus have a public class ProjectAAPIManager : APIManager {} This means that the public Instance-variable in ProjectAAPIManager is actually of type APIManager, not ProjectAAPIManager. The way I'm currently handling this is with a public new PAAPIM Instance { return (PAAPIM)_inst}
– Frank v Hoof
Nov 22 at 18:07
I updated my answer with your examples. I think the problem is your usage of the singleton class. In a singleton, your instance should be private. You should only have a public property that will return your instance if it exists, or create a new one if it doesn't. Hope this helps!
– slig_3
Nov 22 at 20:30
Inheriting from Singleton is the recommended/advised implementation here, as Unity-Objects (scripts) do not have constructors. They are usually created through a call to AddComponent<ClassType>(). See wiki.unity3d.com/index.php/Singleton
– Frank v Hoof
Nov 22 at 21:44
add a comment |
You should not have classes that implement your generic singleton class.
Otherwise, by default, your protected fields will be accessible by the subclasses (it's what "protected" keyword does)
Instead, you should do something like this:
class Program
{
static void Main(string args)
{
var barInstance = Foo<Bar>.GetInstance();
}
}
public class Foo<T> where T : new()
{
protected bool knowsFu;
private static T _instance;
public static T GetInstance()
{
if (_instance == null)
_instance = new T();
return _instance;
}
}
public class Bar
{
public Bar()
{
}
}
Edit 1:
To use a singleton, you should not make another class implement the singleton behavior (This is not how the singleton pattern works).
To use the same classes as your second example, you should do something like this.
public class SingletonBehaviour<T> where T : new()
{
public static T Instance
{
get
{
if(instance == null)
instance = new T()
return instance;
}
}
private static T instance { get; set; }
}
public class APIManager // This class should not inherit from the SingletonBehavior class
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
public class ProjectAAPIManager : APIManager
{
public ProjectAAPIManager GetInstance() => SingletonBehavior<ProjectAAPIManager>.Instance();
}
the knowsFu is actually the _instance in my case.. I have a 'generic' API-manager, that has things like my accesskey, HTTPPost-methods, etc. This class inherits my Singleton-GenericClass public class APIManager : SingletonBehaviour<APIManager>{} However, this functionality is used in multiple of my projects. I thus have a public class ProjectAAPIManager : APIManager {} This means that the public Instance-variable in ProjectAAPIManager is actually of type APIManager, not ProjectAAPIManager. The way I'm currently handling this is with a public new PAAPIM Instance { return (PAAPIM)_inst}
– Frank v Hoof
Nov 22 at 18:07
I updated my answer with your examples. I think the problem is your usage of the singleton class. In a singleton, your instance should be private. You should only have a public property that will return your instance if it exists, or create a new one if it doesn't. Hope this helps!
– slig_3
Nov 22 at 20:30
Inheriting from Singleton is the recommended/advised implementation here, as Unity-Objects (scripts) do not have constructors. They are usually created through a call to AddComponent<ClassType>(). See wiki.unity3d.com/index.php/Singleton
– Frank v Hoof
Nov 22 at 21:44
add a comment |
You should not have classes that implement your generic singleton class.
Otherwise, by default, your protected fields will be accessible by the subclasses (it's what "protected" keyword does)
Instead, you should do something like this:
class Program
{
static void Main(string args)
{
var barInstance = Foo<Bar>.GetInstance();
}
}
public class Foo<T> where T : new()
{
protected bool knowsFu;
private static T _instance;
public static T GetInstance()
{
if (_instance == null)
_instance = new T();
return _instance;
}
}
public class Bar
{
public Bar()
{
}
}
Edit 1:
To use a singleton, you should not make another class implement the singleton behavior (This is not how the singleton pattern works).
To use the same classes as your second example, you should do something like this.
public class SingletonBehaviour<T> where T : new()
{
public static T Instance
{
get
{
if(instance == null)
instance = new T()
return instance;
}
}
private static T instance { get; set; }
}
public class APIManager // This class should not inherit from the SingletonBehavior class
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
public class ProjectAAPIManager : APIManager
{
public ProjectAAPIManager GetInstance() => SingletonBehavior<ProjectAAPIManager>.Instance();
}
You should not have classes that implement your generic singleton class.
Otherwise, by default, your protected fields will be accessible by the subclasses (it's what "protected" keyword does)
Instead, you should do something like this:
class Program
{
static void Main(string args)
{
var barInstance = Foo<Bar>.GetInstance();
}
}
public class Foo<T> where T : new()
{
protected bool knowsFu;
private static T _instance;
public static T GetInstance()
{
if (_instance == null)
_instance = new T();
return _instance;
}
}
public class Bar
{
public Bar()
{
}
}
Edit 1:
To use a singleton, you should not make another class implement the singleton behavior (This is not how the singleton pattern works).
To use the same classes as your second example, you should do something like this.
public class SingletonBehaviour<T> where T : new()
{
public static T Instance
{
get
{
if(instance == null)
instance = new T()
return instance;
}
}
private static T instance { get; set; }
}
public class APIManager // This class should not inherit from the SingletonBehavior class
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
public class ProjectAAPIManager : APIManager
{
public ProjectAAPIManager GetInstance() => SingletonBehavior<ProjectAAPIManager>.Instance();
}
edited Nov 22 at 20:25
answered Nov 22 at 17:58
slig_3
13
13
the knowsFu is actually the _instance in my case.. I have a 'generic' API-manager, that has things like my accesskey, HTTPPost-methods, etc. This class inherits my Singleton-GenericClass public class APIManager : SingletonBehaviour<APIManager>{} However, this functionality is used in multiple of my projects. I thus have a public class ProjectAAPIManager : APIManager {} This means that the public Instance-variable in ProjectAAPIManager is actually of type APIManager, not ProjectAAPIManager. The way I'm currently handling this is with a public new PAAPIM Instance { return (PAAPIM)_inst}
– Frank v Hoof
Nov 22 at 18:07
I updated my answer with your examples. I think the problem is your usage of the singleton class. In a singleton, your instance should be private. You should only have a public property that will return your instance if it exists, or create a new one if it doesn't. Hope this helps!
– slig_3
Nov 22 at 20:30
Inheriting from Singleton is the recommended/advised implementation here, as Unity-Objects (scripts) do not have constructors. They are usually created through a call to AddComponent<ClassType>(). See wiki.unity3d.com/index.php/Singleton
– Frank v Hoof
Nov 22 at 21:44
add a comment |
the knowsFu is actually the _instance in my case.. I have a 'generic' API-manager, that has things like my accesskey, HTTPPost-methods, etc. This class inherits my Singleton-GenericClass public class APIManager : SingletonBehaviour<APIManager>{} However, this functionality is used in multiple of my projects. I thus have a public class ProjectAAPIManager : APIManager {} This means that the public Instance-variable in ProjectAAPIManager is actually of type APIManager, not ProjectAAPIManager. The way I'm currently handling this is with a public new PAAPIM Instance { return (PAAPIM)_inst}
– Frank v Hoof
Nov 22 at 18:07
I updated my answer with your examples. I think the problem is your usage of the singleton class. In a singleton, your instance should be private. You should only have a public property that will return your instance if it exists, or create a new one if it doesn't. Hope this helps!
– slig_3
Nov 22 at 20:30
Inheriting from Singleton is the recommended/advised implementation here, as Unity-Objects (scripts) do not have constructors. They are usually created through a call to AddComponent<ClassType>(). See wiki.unity3d.com/index.php/Singleton
– Frank v Hoof
Nov 22 at 21:44
the knowsFu is actually the _instance in my case.. I have a 'generic' API-manager, that has things like my accesskey, HTTPPost-methods, etc. This class inherits my Singleton-GenericClass public class APIManager : SingletonBehaviour<APIManager>{} However, this functionality is used in multiple of my projects. I thus have a public class ProjectAAPIManager : APIManager {} This means that the public Instance-variable in ProjectAAPIManager is actually of type APIManager, not ProjectAAPIManager. The way I'm currently handling this is with a public new PAAPIM Instance { return (PAAPIM)_inst}
– Frank v Hoof
Nov 22 at 18:07
the knowsFu is actually the _instance in my case.. I have a 'generic' API-manager, that has things like my accesskey, HTTPPost-methods, etc. This class inherits my Singleton-GenericClass public class APIManager : SingletonBehaviour<APIManager>{} However, this functionality is used in multiple of my projects. I thus have a public class ProjectAAPIManager : APIManager {} This means that the public Instance-variable in ProjectAAPIManager is actually of type APIManager, not ProjectAAPIManager. The way I'm currently handling this is with a public new PAAPIM Instance { return (PAAPIM)_inst}
– Frank v Hoof
Nov 22 at 18:07
I updated my answer with your examples. I think the problem is your usage of the singleton class. In a singleton, your instance should be private. You should only have a public property that will return your instance if it exists, or create a new one if it doesn't. Hope this helps!
– slig_3
Nov 22 at 20:30
I updated my answer with your examples. I think the problem is your usage of the singleton class. In a singleton, your instance should be private. You should only have a public property that will return your instance if it exists, or create a new one if it doesn't. Hope this helps!
– slig_3
Nov 22 at 20:30
Inheriting from Singleton is the recommended/advised implementation here, as Unity-Objects (scripts) do not have constructors. They are usually created through a call to AddComponent<ClassType>(). See wiki.unity3d.com/index.php/Singleton
– Frank v Hoof
Nov 22 at 21:44
Inheriting from Singleton is the recommended/advised implementation here, as Unity-Objects (scripts) do not have constructors. They are usually created through a call to AddComponent<ClassType>(). See wiki.unity3d.com/index.php/Singleton
– Frank v Hoof
Nov 22 at 21:44
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53435884%2fc-protected-variables-inside-of-a-generic-class-can-be-accessed-by-a-different%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
protected bool knowsFu { get; private set; }
?– stuartd
Nov 22 at 17:35
Yeah.. That's what I'm using now.. However, what if I need a protected (inner) set as well?
– Frank v Hoof
Nov 22 at 17:48
"A protected member is accessible within its class and by derived class instances."
– stuartd
Nov 22 at 17:52