Hi trying to make a class inside a static class to use in JINT but when it's referenced I get an error
C# code
namespace Hi {
public static class Ok {
public class Wowa {
public Wowa(){}
}
}
}
But when I try to make a new one in JavaScript I get an error "the object cannot be used as a constructor" from JINT
var k = new Hi.Ok.Wowa()
Am I doing this right? How can I set up the C# to be able to use the above code in JavaScript from JINT?
BTW IF instead of "Ok" being a static class, rather a namespace, it works, but I want it as a class because I want to have static methods in it also
you cant use none-static class in a static class (ReadThis) but if you remove (static) in your frist class
namespace Hi {
public class Ok {
public class Wowa {
public Wowa(){}
}
}
}
and it can be said that it does not make much difference because (Static) only makes subcategories of your class have to use (Static).
But if you want your class to be impossible to build on variables, you can use abstract(ReadThis)
namespace Hi {
public abstract class Ok {
public class Wowa {
public Wowa(){}
}
}
}
and
Main()
{
Ok k = new Ok();//Error
}
Imagine you have this:
namespace Hi
{
public static class Ok
{
public class Wowa
{
public Wowa() { }
public static string MyStaticMethod() => "Hello from 'Static Method'";
public string MyNormalMethod() => "Hello from 'Normal Method'";
}
}
}
It's possible to use non-static class Wowa by making an instance of it , and then you can call MyNormalMethod of that instance (you can only call not-static method within instance of that class).
Hi.Ok.Wowa wowa = new Hi.Ok.Wowa();
wowa.MyNormalMethod();
And without making any instance of Wowa you can call static method within it, like this:
Hi.Ok.Wowa.MyStaticMethod();
Finally you can see working code here.
Related
I'm trying to extend a generic type class, but I can't get VS to see the extension methods.
Of course there would be many ways around this and it sure isn't best practice in all situations, but I can't figure out why, of the two apparently identical cases below, the first one works and the other doesn't.
First, an example of a successful attempt to extend the List class (just to prove I can handle the basics):
namespace Sandbox.ExtensionsThatWork
{
public static class ListExtensions
{
public static List<TheType> ExtendedMethod<TheType>(this List<TheType> original)
{
return new List<TheType>(original);
}
}
public class ExtensionClient
{
public void UseExtensionMethods()
{
List<string> a = new List<string>();
List<string> b = a.ExtendedMethod();
}
}
}
However, the object I want to extend is something like this
namespace Sandbox.Factory
{
public class Factory<T>
{
public static Thing<T> Create()
{
return new Thing<T>();
}
}
public class Thing<T>{}
public static class FactoryExtensions
{
internal static Thing<FactoryType> CreateFake<FactoryType>(this Factory<FactoryType> original)
{
return new FakeThing<FactoryType>();
}
}
public class FakeThing<T> : Thing<T>{}
}
And in this case I can't for the life of me get the compiler to see the extension method.
namespace Sandbox.FactoryClients
{
public class FactoryClient
{
public void UseExtensionMethods()
{
Factory.Thing<int> aThing = Factory.Factory<int>.Create();
///THE COMPILER WON'T FIND THE CreateFake METHOD
Factory.Thing<int> aFakeThing = Factory.Factory<int>.CreateFake<int>();
}
}
}
What am I missing?
Thank you all for your time.
Your problem has nothing to do with generics.
You're calling the extension as if it were a static method of Factory.Factory<int>, which it cannot be.
C# does not support extension static methods (meaning extension methods that act like static methods of the type of the this parameter) on any type.
You need an instance to call the extension method on (like you do in your "working" example):
using Sandbox.Factory;
public void UseExtensionMethods()
{
Thing<int> aThing = Factory<int>.Create();
Thing<int> aFakeThing = new Factory<int>().CreateFake();
}
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?
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.
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();
}
There are two files A.cs and B.cs. There is a method fn() which is used in both the classes.
Method fn() is used in both class files. This increases code complexity if I need this method in many class files (say 100 files).
I know that we can call this method by creating an object for the class in which this method is defined. How can I share this function between two or more classes without creating an object every time for accessing this method?
Put the method in a static class:
public static class Utils
{
public static string fn()
{
//code...
}
}
You can then call this in A.cs and B.cs without creating a new instance of a class each time:
A foo = new A();
foo.Property = Utils.fn();
Alternatively, you could create a BaseClass that all classes inherit from:
public class BaseClass
{
public BaseClass() { }
public virtual string fn()
{
return "hello world";
}
}
public class A : BaseClass
{
public A() { }
}
You would then call fn() like so:
A foo = new A();
string x = foo.fn();
I hope the function isn't really called fn(), but actually named to what it does, like CalculateTotal(). Then you can extract this method into a class, say: TotalCalculator.
Now upon application startup, preferably using dependency injection, you create one instance of the class that gets shared between objects that require it. Like so:
class TotalCalculator
{
public int Calculate()
{
return 42;
}
}
class NeedsCalculator1
{
TotalCalculator _calculator;
public NeedsCalculator1(TotalCalculator calculator)
{
_calculator = calculator;
}
public void Foo()
{
_calculator.Calculate();
}
}
class NeedsCalculatorToo
{
TotalCalculator _calculator;
public NeedsCalculatorToo(TotalCalculator calculator)
{
_calculator = calculator;
}
public void Bar()
{
_calculator.Calculate();
}
}
Then you instantiate the calculator once, and pass it into the other classes' constructor:
TotalCalculator calculator = new TotalCalculator();
NeedsCalculator1 dependency1 = new NeedsCalculator1(calculator);
NeedsCalculatorToo dependency2 = new NeedsCalculatorToo(calculator);
You can now further abstract the calculator dependency by creating a base class containing the constructor and a protected TotalCalculator instance field, for example.
Assuming that this method is self contained, you could create a static class and put this method as a static method in it, which is in turn, called by the other classes.
If is is not self contained, you could try and declare it in some super class and let the other 100 classes extend that class.
I have the following code:
class EmployeeFactory
{
public enum EmployeeType
{
ManagerType,
ProgrammerType,
DBAType
}
}
I want to access this in MAIN class (Program). I have written the following code. IT WORKS. But I want to know how I can access the ENUM without instantiating the class -- Means ENUM is like a static variable (Class Level Variable) ? Any help ?
class Program
{
static void Main(string[] args)
{
Console.WriteLine(EmployeeFactory.EmployeeType.ProgrammerType); // WORKS WELL
}
}
or do I need to write it this way?
EmployeeFactory ef = new EmployeeFactory();
ef.EmployeeType.ProgrammerType
You can access it simply using the class.
EmployeeFactory.EmployeeType.ProgrammerType
The enum is part of the class, not part of a class instance.
But I want to know how I can access the ENUM without instantiating the class
The original way you're accessing this enum
Console.WriteLine(EmployeeFactory.EmployeeType.ProgrammerType);
already accomplishes that; you are accessing the enum without instantiating the class.
try something like this ...
public interface IEnums
{
public enum Mode { New, Selected };
}
public class MyClass1
{
public IEnums.Mode ModeProperty { get; set; }
}
public class MyClass2
{
public MyClass2()
{
var myClass1 = new MyClass1();
//this will work
myClass1.ModeProperty = IEnums.Mode.New;
}
}
or
you can directly access like this....
EmployeeFactory.EmployeeType.ProgrammerType
i hope it will helps you
This is a noob question
using System.name;
class class_name
{
private className Obj;
public class_name()
{
}
public function()
{
Obj.function <----- why i cant acesss the global varible here ??
}
}
When i type the class the instellisence docent show any thing :-s
I'm assuming there was just some confusion with the names and, by function, you meant class_name, or instead of class_name you meant className.
In order to access a method this way, it must be declared as static. Otherwise, you must first create an instance of the class and access the method through the instance.
EDIT The code you posted is very confusing. The following works just fine for me.
class Class1
{
public void Function1()
{
}
}
class Class2
{
private Class1 obj;
public void Function2()
{
obj.Function1();
}
}
Have you instantiated that class?