Why can't I access public property field in static class - c#

I'm trying to figure out why this is not working...
public static class ApplicationType
{
private static ApplicationEnum application = ApplicationEnum.App1;
public static ApplicationEnum Application
{
get { return application; }
set { application = value; }
}
public enum ApplicationEnum
{
App1,
App2,
App3
}
}
I want to access Application from another class, such as...
public partial class MainWindow : Window
{
ApplicationType. //<-- Intellisense shows only ApplicationEnum }
Thanks.
EDIT: Problem was that I was not trying inside the MainWindow as in this example as I thought I was.

You're in the middle of a class declaration. You need to declare a field, method etc. For example, this should be fine (if you make ApplicationEnum public):
private ApplicationEnum foo = ApplicatoinType.Application;
Until you've made ApplicationEnum public, you'll find that your Application property will fail to compile - you can't declare a public property of a type which isn't itself public.

Related

call the function in another class(c#)

I am trying to migrate one of my macOS app to Windows UWP.
There is a requirement that I need to call the function in another class
namespace MyApp
{
public sealed partial class MainPage : Page
{
public bool isOk;
public MainPage()
{
}
public void doSomething(){
};
/*
public static void doSomething(){
isOk=false;// isOk is inaccessible
};*/
}
public sealed partial class AnotherPage : Page
{
public AnotherPage()
{
//call doSomething() in MainPage
}
}
}
it is very easy to implement this in objective-c via protocol(interface)
but in c#, the mechanism of the interface is different from the objective-c protocol.
of course, I can use the code below
MainPage mainPage=new MainPage();
mainPage.dosomthing();
but I wonder if this is valid for Page object related to the XAML file.
or there is a common usage to call the function in another class?
Your comment welcome
NOTE: This is an answer to your question but from a design perspective this is bad.
You need a reference to the instantiated MainPage. I'm sure there's one in the framework but for example just so this can be understood let's make a public static class to hold this reference.
public static class Global
{
public static Page MainPage { get; set; }
}
Now in the MainPage constructor assign itself to this property of the static Global class.
public MainPage()
{
Global.MainPage = this;
}
Now from any other page you can access it.
public AnotherPage()
{
Global.MainPage.doSomething();
}

How can I access a list that is created in a static object that is part of another class?

What I would like to do is to have a list that is in an object counts that is defined in the App class as a static when my application starts:
Here's the object:
public class Counts
{
public Counts()
{
public static List<CntQty> CardClicks2m;
}
}
In my application I declare this
am using the following code:
public partial class App : Application
{
public static Counts counts = new Counts();
public App()
{
}
}
Now I try to use load some data into the list but it gives me the error below. Note that this function is in another class.
public void GetClickHistory()
{
App.counts.CardClicks2m = db2.Query<CntQty>(sql);
The last line of the code is giving me an error saying
counts.CardClicks2m cannot be accessed with an instance reference;
qualify it with a type name instead.
I have tried a few different ways to make this work. One by removing the static and creating the object in the app constructor. This also didn't seem to work so I am hoping someone can point me in the right direction or at least suggest something.
i guess scope of variable is not right , you need to do like this
public class Counts
{
public static List<CntQty> CardClicks2m;
public Counts()
{
}
}
The error is pretty self explanatory, you cannot access a static property using an instance variable. all you need to do is use the typename. So this:
App.Counts.CardClicks2m
Becomes this:
Counts.CardClicks2m
You may need to specify the full namespace of the Counts class:
Some.Namespace.Counts.CardClicks2m
The error you are receiving is because you are trying to access to a static member from a instance object
public void GetClickHistory()
{
App.counts.CardClicks2m = db2.Query<CntQty>(sql);
EDITED after comments:
Try this (accessing the static member from the class):
public void GetClickHistory()
{
Counts.CardClicks2m = db2.Query<CntQty>(sql);
As CardClicks2m is declared static, it must be accessed from the class scope. If Counts class doen't have any other code, you can declare
public static class Counts
And there is not neccesary to create an instance of counts
public static Counts counts = new Counts(); //this is not neccesary
As your CardClicks2m-member is static there´s no need to have any instance of your Counts- or aven your App-class. The member exists once per appdomain however. Having said this in order to access CardClicks2m you don´t have to create an instance of your Counts-class within App.
Use this instead:
class MyClass
{
void DoSometjing()
{
Counts.CardClicks2m = db2.Query<CntQty>(sql).ToList();
}
}
Be aware to that Query will surely not return a List<CntQty>, but an IQueryable<CntQty>, that´s why you should call ToList afterwards.
Furthermore you can´t declare a member within a method or constructor. Thus declare it within the class´-body instead of the constructor:
public class Counts
{
public static List<CntQty> CardClicks2m;
public Counts() { /* any further initialzation */ } }
}

Incompatibility accessibility error, what is that means?

I have a class Computer.cs, which belongs to the form Computer, and I have an independent class Indicators.
In my code I'm getting an error:
Incompatibility accessibility: accessibility return type "WF.Code.Indicators"
method is below than accessibility return type "WF.Computer.ShowForm ()"
What is that means?
Computer.cs
namespace WF
{
public partial class Computer : Form
{
Code.Indicators indicators = new Code.Indicators();
public Computer()
{
if (indicators.isComputerAlreadyRunning == false)
{
InitializeComponent();
indicators.isComputerAlreadyRunning = true;
}
}
public Code.Indicators ShowForm() // Error
{
return new Code.Indicators(indicators.isComputerAlreadyRunning);
}
}
}
Indicators.cs
namespace WF.Code
{
class Indicators
{
public Indicators(bool isComputerAlreadyRunning)
{
this.isComputerAlreadyRunning = isComputerAlreadyRunning;
}
public bool isComputerAlreadyRunning = false;
}
}
Your method:
public Code.Indicators ShowForm() // Error
{
return new Code.Indicators(indicators.isComputerAlreadyRunning);
}
It returns an Indicators object and is of public visibility. However the type Indicators itself is not public, it's internal (by default, since you did not specify it ; see this answer for more information).
Declare the class Indicators as public to solve the issue, or set the method ShowForm as internal.
Edit:
To better explain why the compiler complains, imagine your code is actually compiled to a library. Somebody includes this library from another assembly to use it, and this somebody is going to call this public method ShowForm(because he can!).
He is going to get a reference pointing to an Indicators but from his point of view (actually from his assembly's point of view), he does not know what the class Indicators is, because its visibility is internal (as I said, by default). internal elements are not exposed to other assemblies on the contrary of public elements. This creates an incoherence and that it the reason why the compiler complains.
It means that since ShowForm is public the return type must also be public.
you Indicators class is now :
namespace WF.Code
{
class Indicators
{
public Indicators(bool isComputerAlreadyRunning)
{
this.isComputerAlreadyRunning = isComputerAlreadyRunning;
}
public bool isComputerAlreadyRunning = false;
}
}
but should be :
namespace WF.Code
{
public class Indicators
{
public Indicators(bool isComputerAlreadyRunning)
{
this.isComputerAlreadyRunning = isComputerAlreadyRunning;
}
public bool isComputerAlreadyRunning = false;
}
}
in .NET if you instantiate a class outside the class' area then either should be internal or public code access.. otherwise such like you created class as private ( if there is no code access implementation as your implementation of Indicators - class Indicators- compiler accept that as private and you can't access out of the class)
Even if it was internal code access and you refer it as public you will get the same exception..
when your class' code access is public then should be all instances / inside methods or calls should be public, if it is internal then can be internal or private or protected

Is it possible to create an instance of an class without running ANY code from the class? (no ctor, no field initializations)

I have created an engine that takes in 3rd party plugins (DLL's) that implement an interface.
Since I have no control over the code that gets plugged in, I want to be able to run 1 specific method (from the interface) from the correct class (GetTypes loop untill I find the interfaced class ).
Since anyone can create nice constructor code that executes on Activator.CreateInstance, I can solve that by using FormatterServices.GetUninitializedObject. But that does not help when code is being initialized on fields in the class.
public class myclass : myinterface {
public someotherclass name = new someotherclass()
public myclass() {
//Unknown code
}
//I only want this run.
public string MyProperty{
get {
return "ANiceConstString";
}
}
}
The problem with both ways (CreateInstance/GetUninitializedObject) is that the constructor of someotherclass will be run.
Before you start analyze my needs. This is only run in the initializing of the engine to get a set of standard values. If this get'er relies on other initialized values the "plugin" will be marked as failed as there is no valid value returned. If not marked as failed, later on the class will be loaded properly with Activator.CreateInstance().
So stick to this question:
Does .Net support any way to create an 100% non-initialized class?
Update for the answers. I tested this before I posted my question.
For the answer that someotherclass wont run, I allready tested that and it is run if static.
public class myclass : myinterface {
static Tutle test;
public myclass () {
test = new Tutle();
}
public class Tutle {
public Tutle() {
MessageBox.Show("RUN!");
}
}
}
CreateInstance shows the messagebox. GetUninitializedObject does not.
public class myclass : myinterface {
static Tutle test = new Tutle();
public myclass () {
}
public class Tutle {
public Tutle() {
MessageBox.Show("RUN!");
}
}
}
CreateInstance shows the messagebox. GetUninitializedObject shows the messagebox.
Is there a way to get around static field intializers and ctors?
Simply:
var obj = (myclass)FormatterServices.GetUninitializedObject(typeof(myclass));
That will not run the constructor / field initializers. At all. It will not run the constructor for someotherclass; name will be null.
It will, however, execute any static constructor that exists, if necessary under standard .NET rules.
HOWEVER! I should note that this method is not intended for ad-hoc usage; its primary intent is for use in serializers and remoting engines. There is a very good chance that the types will not work correctly if created in this way, if you have not subsequently taken steps to put them back into a valid state (which any serializer / remoting engine would be sure to do).
As an alternative design consideration:
[SomeFeature("ANiceConstString")]
public class myclass : myinterface {
public someotherclass name = new someotherclass()
public myclass() {
//Unknown code
}
}
Now you can access the feature without instantiation; just use:
var attrib = (SomeFeatureAttribute)Attribute.GetCustomAttribute(
type, typeof(SomeFeatureAttribute));
string whatever = attrib == null ? null : attrib.Name;
with:
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum)]
public sealed class SomeFeatureAttribute : Attribute
{
private readonly string name;
public string Name { get { return name; } }
public SomeFeatureAttribute(string name) { this.name = name; }
}

Access variable from other namespaces

I am trying to set/read a variable in class bluRemote from another namespace/class like so:
namespace BluMote
{
class bluRemote
{
public string cableOrSat = "CABLE";
........
}
}
and the other cs file (which is the form):
namespace BluMote
{
public partial class SettingsForm : Form
{
if (BluMote.bluRemote.cableOrSat == "CABLE")
{
BluMote.bluRemote.cableOrSat = "SAT";
}
.......
}
}
I know i am doing it wrong but I'm more used to doing stuff like this in VB so its like night and day ha :o)
What you are trying to do is work with static variables so you would need to change your class to this:
namespace BluMote
{
public static class bluRemote
{
public static string cableOrSat = "CABLE";
........
}
}
It is better if you stay away from static classes (for the most part) and instead focus on an object oriented approach where you have an instance (object) of bluRemote.
So instead of making the bluRemote class static you keep it the same and do:
public partial class SettingsForm : Form
{
private bluRemote _remote = new bluRemote(); // possibly created somewhere else
public void SomeFunction()
{
if (_remote.cableOrSat == "CABLE")
{
_remote.cableOrSat = "SAT";
}
}
.......
}
You're trying to access an instance variable - i.e. one which has a potentially different value for each object - just by class name. That only works for static variables.
You need to have an instance of bluRemote, and ask that for its value. However, I would strongly suggest that:
You rename your class to follow .NET naming conventions
You don't make variables public; use properties
Also note that there's only one namespace here - BluMote. Both of your classes are declared in that namespace.
As you've declared the cableOrSat field, you'll need to set it on an instance of the bluRemote class, but you are trying to set it using the name of the class itself.
If you declare the cableOrSat field as:
public static string cableOrSat = "CABLE";
You will be able to access it through the class name itself.

Categories

Resources