My problem is this, I wanted to have a bunch of variables which I called GlobalVariables that I can use and change on demand. I used dictionary for that which was rather usefull however 2 problems arose. First that I can use only one type and second is that later I wanted to use those variables in multiple class.
My next solution was to use separate class to define variables there and use them like GlobalStatus.Variable. Seemed like a good idea however now I am faced with the problem that I need to call my GlobalStatus variables by other variable. I can't put it into words(thats the reason why I am asking this question) but here is how it was done with Dictionary.
foreach (string String in Array) {
if (GlobalStatus[String] == "Test") {
...
}
}
Can I emulate this behavour using Class to store variables, or I should use another way to store said variables?
As David pointed out you probably wanna avoid global variables unless you have a good reason to have them.
That said, if I were you I'd probably make something like
namespace Global{
public class Options{
public static Options _Instance;
void Awake(){
if (_Instance == null)
{
_Instance = this;
}
}
}
}
Then you may call this global Options class from anywhere using the Singleton _Instance variable by saying Global.Options._Instance.*Your variable or method*
This way you can have a namespace called Global which can hold your global variables in an orderly fashion.
I advise you to divide your variables into classes instead of having a dictionary to hold it all, unless there is good reason to.
The task is:
We have an array of 2 strings: name and value. This is called requirement. Requirements are kept in global class as static variables. How to compare requirement in the class with a requirement parameter like new array string[2].
After some discussion one of possible solutions
Use array of requirements in global class
Use requirement name as integer instead of string type.
Then requirement name can be used as index of global array.
Related
I am fairly new to C# programming (and programming in general). I want to use a variable in two different methods I thought I needed to declare the variable just inside the class but I keep getting this error message "Error: A field initializer cannot reference the non-static field, method, or property" I am sure it is a relatively simple error on my part, but how do I fix this?
After researching online for awhile I think I am on the right track of understanding classes but my understanding is obviously lacking.`
public partial class MainPage : ContentPage
{
public string path = diceNumber.SelectedItem.ToString();
public MainPage()
{
InitializeComponent();
}
private void DiceRollResult_Clicked(object sender, EventArgs e)
{
if (path == "One")
{
DisplayAlert("One", "You Lost", "Close");
}
else if (path=="Two")
{
DisplayAlert("Two", "You Lost", "Close");
}
else if (path == "Three")
{
DisplayAlert("Three", "You Won", "Close");
}
// The else if statements are just to show you how I am using the code.
A few things for you to understand here:
If you assign a value to a class-level variable, it is executed before any other part of the class. So diceNumber.SelectedItem won't even exist at the time when path is being initialized. That is the cause of your error. You can only use static fields or values to assign to a class-level variable for initialization (because static members do not need an instance).
Then there is a logical mistake you're making. Even if it were possible to assign diceNumber.SelectedItem to your variable upon startup, you probably don't want to do that, because then it would only be executed once upon startup. What you actually want it to do is to check currently selected value at the time of click and then respond accordingly. Therefore you should move your path variable inside the click handler because I don't see you're using it anywhere else.
Lastly, if you need to access this value in other functions too, you can create local variables inside those functions just like this:
string path = diceNumber.SelectedItem.ToString();
in all the functions where you need this. No need of a global variable.
In essence, diceNumber (which is probably a UI control) itself is a global class-level variable. So it will do everything that your path variable is doing for you. Not sure if this is WinForms or WPF or something else, but you can always see the declaration of these UI controls as class-level variables in the code-behind.
This seems to be a Xamarin.Forms application, its not a good practice to use a variable in several methods you would generally use a class and instantiate that class throughout the lifespan of your program.
You can access a variable from any other class or form by making it a static variable.
public static string path = diceNumber.SelectedItem.ToString();
Now in any class or in any method, you can access the variable by
var s = MainPage.path;
The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of an object unless it is explicitly passed in a method parameter.
cant quite understand how class work
class Class1{
private int a;
for(a=0;a<10;a++){}
// how can a be out of scope?
}
and why i can do this
class Class1{
private int a;
void tera()
{
private string aiha="lk"; //commenting this out ,makes it work why??
for(a=0;a<10;a++){}
}
}
1st part : can a class have only methods and fields? why?
2nd part: cant methods have declarations?
i know this might be a poor explanation but i cant wrap my head around .
For the first part, you haven't defined a method name so it wont work, you can't place the method's body inside a class without declaring a method.
class Class1{
private int a = 0;
void Example() {
for(a=0;a<10;a++){}
}
}
Would work
For the second part, it wouldn't make sense as variable is only available inside the method's scope so its meaningless to give it a modifier.
You can read more about classes here but basically its a group of members and methods that are usually gonna be used every time you create an instance of that class.
1st.
(Classes are basic constructs of .NET Framework.)
Because it's object oriented it can only contain MEMBERS like methods, fields, constants, properties, and events as single units .
(note: also members must be declared within a type).
2nd
In C# there are no global variables or methods as there are in some other languages.
and i think since c# considers a method as a single object you cannot try give different access to its variables, it will think you are trying to create another member for the class.
I am new to C#. Come from the C/C++ environment. My application has a List<Model> which is required all over the place, by different classes. The problem is that a copy will not do because this statement:
dataGrid.ItemsSource = myModelList;
requires the original by address. I tried changing some arguments around and passing that particular variable as ref but as soon as it is assigned with an equal sign, I end up with a copy. Correct?
You could make it a singleton.
However a concrete List needed all over the place would make me have a serious think about my design.
At the very least you should consider writing a class to control access to the list (add, remove, clear etc), and making that "global", otherwise you are going to be in deep in the brown stuff, until it hits the fan.
Create a Public Class and have the content you wish to pass declared static within the class. Then just access it as NameOfClass.NameOfMethod()
public class NameOfClass
{
public static RETURNTYPE NameOfMethod()
{
// Your Code
}
}
You can create a public class for it with a public static List inside it. That one you then can access everywhere.
eg
public class FakeGlobal
{
public static List<Model> MyModelList = new List<Model>();
}
or even make it a property with getter/setter.
I am developing C# and asp.net web application.
I have general class called utilities, I have lot of public and static variables in this public utilities class.
Since this number is gradually increasing, I want to know is it good practice to store utilities methods and variable as public static.
Example of my code
public class utilities
{
public static string utilVariable1 = "Myvalue";
public static string utilVariable2 = "Myvalue";
public static string utilVariable3 = "Myvalue";
:
public static string utilVariableN = "Myvalue";
public static string UtilMethod1()
{
//do something
}
public static string UtilMethod2()
{
//do something
}
public static string UtilMethodN()
{
//do something
}
}
There's nothing inherently wrong with static classes, although they should typically not have state (fields). Your use of public static fields indicates that this is not the case, so it seems like you are using abusing the static keyword slightly. If your class needs to have state, then it should be a normal, non-static class, and you should create instances of it. Otherwise, the only public fields visible on the class should be const (consider the Math class, with constants such as Math.PI - a good use of static methods and fields).
Another consideration is cohesion. Methods typically exist grouped in one class because they are closely related in one way or another. Again, the Math class is a good example; everything in there has to do with maths. At some point, you would want to split your global utility class into multiple smaller, more focussed ones. See Wikipedia for some examples on cohesion, it sounds like your usage falls under "Coincidental cohesion (worst)".
There's nothing wrong with this approach for methods, but variables should really be const if they're going to be static and public. If they are subject to change then you should look at a different structure for variables that are being manipulated by more than one component.
Personally, I'm a fan of the Singleton pattern.
static is not a bad thing per se. Methods that don't need to access any member variables or methods should always be declared static. That way the reader of the code sees immediately that a method won't change member variables or methods.
For variables the situation is different, you should avoid static variables unless you make them const. Public static variables are globally accessible and can easily raise issues if multiple threads access the same variable without proper synchronization.
It is hard to tell for your case if it's a good or a bad idea to use statics, because you didn't provide any context information.
Creating one class to do it all is not a good practice, and it's recommended to structure your project, and keep stuff that belongs to each other separated from the randomness.
A great example of this was a project I took over from a co-worker. There was 1 class, called Methods. It contained over 10K lines of methods.
I then categorized them into approx. 20 files, and the structure was restored.
Most of the methods from that project were validating user input, which can easily be moved into a static class Validation.
One awful thing I notice is the mutable public and static variables. This is bad for several reasons:
Incorrect behavior, because if some method changes this, while it isn't supposed to do that, it causes other methods to behave improperly, and it's really hard to track down/debug.
Concurrency, how are we going to ensure thread safety? Do we let it over to all methods that work with that? Say if it's a value type, what will we let them lock on? What if some method forgets to make it thread safe?
Expand-ability (I hope you understand what I mean with that), if you have for example a static class data that stores all these public static variables, that you shouldn't have. It can store that once, if for example you might change your application structure a bit, and say want to make it possible to load two projects in the same screen, then it's very difficult to make that possible, because you can't create two instances of a static class. There is only one class, and it'll remain like that.
For number 3 a cleaner solution would be to store either a list of instances of a data class, or to store a reference to the default and/or active data class.
Static member, and private static members (or protected) are a good practice, as long as you don't make huge classes, and the methods are related.
Public and static variables are okay if they're not really variable.
The two ways to do this is by marking them constant (const modifier) or readonly (readonly modifier).
Example:
public class UtilitiesClass
{
internal UtilitiesClass() { }
public void UtilityMethod1()
{
// Do something
}
}
// Method 1 (readonly):
public static readonly UtilitiesClass Utilities = new UtilitiesClass();
// Method 2 (property):
private static UtilitiesClass _utilities = new UtilitiesClass();
public static UtilitiesClass Utilities
{
get { return _utilities; }
private set { _utilities = value; }
}
The advantage of method 1 is that you don't have to worry about thread-safety at all, the value can't change.
Method 2 is not thread-safe (though it's not difficult to make it that), but it has the advantage of allowing the static class itself to change the reference to the utilities class.
No, it is not a good practice for large applications, especially not if your static variables are mutable, as they are then effectively global variables, a code smell which Object Oriented Programming was supposed to "solve".
At the very least start by grouping your methods into smaller classes with associated functionality - the Util name indicates nothing about the purpose of your methods and smells of an incoherent class in itself.
Second, you should always consider if a method is better implemented as a (non-static) method on the same object where the data that is passed as argument(s) to the method lives.
Finally, if your application is quite large and/or complex, you can consider solutions such as an Inversion of Control container, which can reduce the dependency on global state. However, ASP.Net webforms is notoriously hard to integrate into such an environment, as the framework is very tightly coupled in itself.
Never seen this done in asp.net, but never the less, can I define functions without being part of the class?
What I would like to have is a utility library. Currently I have Utils class and every time I need to use it for things like populating drop down lists i have to create and init the Utils() object...any way around that hassle aside from declaring the class static which I would rather not do as I access session in it?
I am using c#, not VB.
Thanks
There's no way to have methods outside of classes.
The typical solution in your case is to create a Utility class full of static methods...that way you don't have to worry about creating an instance of the class to utilize its methods.
And like Joel mentioned...you can still access the session from a static method.
You can always use Extension Methods.
http://msdn.microsoft.com/en-us/library/bb383977.aspx
You can then add the methods on to the existing objects.
You could also create a base class which all your pages inherit from and have that contain the methods you need. It's still part of a class, but you don't need to instantiate a new one, or use static methods.
You can still access Session variables in a static class. One way might be like this:
public static class Utils
{
private static HttpSessionState Session
{
get { return HttpContext.Current.Session; }
}
public static string DoThing(string input)
{
// here you can access session variables like you're used to:
Session["foo"] = input;
}
}
You could have all you pages derive from a BasePage class and put all of your util methods (or wrappers to them) into the base page class
If the class has state then leave it alone. Alternatively, take your state as parameters and then make it static.
You can access the Session variables using HttpContext.Current.Session[], and you can do this from any class (In fact, in many applications I have that use Session variables, I encapsulate all of my session variables in their own class).
Having said that, there is no way to have a method outside of a class, and there really isn't a [good] reason to do so.