I have a public class and need to use one of those variables inside a public static class. Is this possible? If so: how can I call it?
public class xmlData
{
public string testing;
}
public static class fileUpload
{
public static string uploadFile(string file)
// I want to use the testing here
}
You would inject an instance of the xmlData into the method. Like this:
public static string uploadFile(xmlData data, string file)
Now inside that method you can do this:
data.testing ...
To access instance field from static method is not possible. You can pass value as parameter:
public static string uploadFile(string file, string testing)
Or pass object into method:
public static string uploadFile(string file, xmlData data)
{ string testing = data.testing; }
of course it's possible. you just pass it in.
string myString = fileUpload.uploadFile(testing);
All of the methods I can think of in one single spot:
public class xmlData
{
public string testing;
// part of "first option"
public void RunStatic() {
fileUpload.uploadFile(testing);
}
}
public static class fileUpload
{
// used by "option 1, 3"
public static string uploadFile(string testing) {
var firstOption = testing;
}
// used by "option 2"
public static string uploadFile(xmlData myObject, string file) {
var secondOption = myObject.testing;
}
}
public class Program {
public static void Main() {
var objectExample = new xmlData();
// first example
objectExample.RunStatic();
// second example
fileUpload.uploadFile(objectExample, "");
// third example
fileUpload.uploadFile(objectExample.testing);
}
}
All of these will work and should hopefully answer the question. A different question might be whether or not its a good idea to expose instance variables directly or should a property be used. Hm.
Related
Hello I have a lot of variables as I mentioned below, but when I change the value of a variable that I refer to, this change is not adapted by the variables that use this variable.
class PublicVariable
{
public static string ActiveUser = UserInfo.Username;
public static string ActiveUserPath = $#"{Application.StartupPath}\{ActiveUser}";
public static string ActiveUserImg = $#"{ActiveUserPath}\User.png";
}
class UserInfo
{
public static string Username = "-1064548"; //Working
}
class Starting
{
public void Login(string Username, string Pwd)
{
//After the user logged in.
UserInfo.Username = "BruceWayne"; //Working
/* Showing -1064548 = */ MessageBox.Show(PublicVariable.ActiveUser.ToString()); //Not Working.
}
}
For simplicity of the code, ActiveUser is an example.
This code sequence is an example. The goal is to take the data from the database once.
To solve your problem I'd suggest to use properties here. This would look like this then:
class PublicVariable
{
public static string ActiveUser => UserInfo.Username;
public static string ActiveUserPath => $#"{Application.StartupPath}\{ActiveUser}";
public static string ActiveUserImg => $#"{ActiveUserPath}\User.png";
}
class UserInfo
{
public static string Username = "-1064548"; //Working
}
class Starting
{
public void Login (string Username, string Pwd)
{
UserInfo.Username = "BruceWayne";
MessageBox.Show (PublicVariable.ActiveUser.ToString ());
}
}
Alternatively you could use methods as well:
class PublicVariable
{
public static string ActiveUser() => UserInfo.Username;
public static string ActiveUserPath() => $#"{Application.StartupPath}\{ActiveUser()}";
public static string ActiveUserImg() => $#"{ActiveUserPath()}\User.png";
}
class UserInfo
{
public static string Username = "-1064548"; //Working
}
class Starting
{
public void Login (string Username, string Pwd)
{
UserInfo.Username = "BruceWayne";
MessageBox.Show (PublicVariable.ActiveUser().ToString ());
}
}
There actually isn't any major difference between properties and methods. However, fields (you used them) are different, as they don't update their value when the depending value changes. That means, as long as you don't have a reference to the other value (which would be the case for objects, like an object of your class Starting), the field value doesn't update.
So, I have a public partial class called Condensed. Each instance of condensed is supposed to have its own file path which it will load data from, which I tried to create by having a private static string called Path I then create 6 instances of Condensed, but I found out that when I change one of the values of Path that all of the instances of Condensed set their value of Path to the most recent one
public partial class Condensed : UserControl
{
private static string Path;
public Sender Export()
{
//this uses Path to Load data then return it to the main class
}
public void Load(string path)
{
Path = path
}
}
And then inside my main class I do as follows:
public class Main
{
public void Load_Condensed()
{
condensed1.Load(Paths[0]);
condensed2.Load(Paths[1]);
condensed3.Load(Paths[2]);
condensed4.Load(Paths[3]);
condensed5.Load(Paths[4]);
condensed6.Load(Paths[5]);
}
private void exportToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Condensed> Pokemon = new List<Condensed>
{
condensed1.Export(),
condensed2.Export(),
condensed3.Export(),
condensed4.Export(), //Loads all of the data from calling Export()
condensed5.Export(),
condensed6.Export()
};
Export(Condensed); //Sends the data
}
}
Paths[] is just an array of file paths stored as a public array of strings.
Basically I want each instance of Condensed to have its own unique string Path which can be used inside of the instance it is created for, how do i do this?
Your Path-field is static, which means it gets shared between all instances.
Modify it to an instance field to have it different for each instance:
public partial class Condensed : UserControl
{
private string Path; // No static here
public Sender Export()
{
this uses Path to Load data then return it to the main class
}
public void Load(string path)
{
Path = path
}
}
The fact that it is a partial class, doesn't really have anything to do with it. Partial classes just mean that you can define the class in separate files (in this case because it's a usercontrol that needs to set up some code for the UI)
The static is causing your problem because it uses shared memory between all instances of the Condensed class, just remove the static keyword from your property definition.
using System;
namespace ConsoleApp
{
class Program
{
static void Main()
{
var condensed1 = new Condensed() { FilePath = "/filepath1/" };
var condensed2 = new Condensed() { FilePath = "/filepath2/blah/" };
var condensed3 = new Condensed() { FilePath = "/filepath3/blah/blah/" };
Console.WriteLine(condensed1.FilePath);
Console.WriteLine(condensed2.FilePath);
Console.WriteLine(condensed3.FilePath);
Console.ReadKey();
}
}
public partial class Condensed
{
public string FilePath { get; set; }
}
}
Add new constructor like
public Condensed(string path)
{
Path = path
}
And when you create an instance of Condensed class, call it like
Condensed c1 = new Condensed("C/Desktop/blabla");
c1.Export();
public class SampleFile<Toriginal>
{
public SampleFile(File filename,string sname)
{
}
}
How to pass a values to Samplefile constructor?
File is a static class, you can't pass it as a parameter.
Change it to a string:
public class SampleFile<Toriginal>
{
public SampleFile(string filename,string sname)
{
//Here you can use File as it is static
var lines = File.ReadAllLines(filename);
}
}
Then just call it normally:
var sample = new SampleFile<Type>(#"c:\hi.txt", "bye.txt");
With the use of static classes (and constant strings) I want to be able to get constant values like this:
var value = Constants.Labels.Controls.TopNavigation.Save;
I created this structure for this problem:
public static class Constants
{
public static class Labels
{
public static class Controls
{
public static class TopNavigation
{
public const string Save = "Save";
public const string Refresh = "Refresh";
}
}
public static class General
{
public static class Errors
{
public const string UnexpectedError = "An unexpected error occured.";
}
}
}
}
Now the problem is, if I define everything in it, this will grow enormously.
What is the best way to split this into different/partial classes or folder structure so that this keeps maintainable. Keep in mind... To get the value, I always want to obligate the user to start with Constants.Labels....
If possible I would also like one class-file per lowest level...
you could use either resource files or an XML file to store them as key pair.
If the class hierarchy does not provide any value other than organizing the constants, why not just use namespaces?
namespace Constants.Labels.Controls
{
public static class TopNavigation
{
public const string Save = "Save";
public const string Refresh = "Refresh";
}
}
That way you meet your objective of one class-file per lowest level.
The best solution (for now) for this problem was to work with partial classes. Disadvantage: There is some repeating structure for each file. Advantages: When the program expands, this file won't become huge. It's separated in more files AND I need to use the full name to get the correct value. So this was my preferred solution:
------------TopNavigation.cs:------------
public partial class Constants
{
public partial class Labels
{
public partial class Controls
{
public partial class TopNavigation
{
public const string Save = "LABELS_CONTROLS_TOPNAVIGATION_SAVE";
public const string New = "LABELS_CONTROLS_TOPNAVIGATION_NEW";
}
}
}
}
------------Errors.cs:------------
public partial class Constants
{
public partial class Labels
{
public partial class General
{
public partial class Errors
{
public const string Unexpected = "LABELS_GENERAL_ERRORS_UNEXPECTED";
public const string EmptyArgument = "LABELS_GENERAL_ERRORS_EMPTYARGUMENT";
}
}
}
}
If someone should post a better solution to my problem, I'll be happy to accept this as the correct answer.
using System;
namespace Test
{
public class TopNavigationConst {
private const string SAVE = "Save";
private const string REFRESH = "Refresh";
public String Save {get{return SAVE; }}
public String Refresh {get{return REFRESH;}}
}
public class ErrorsConst
{
public const string UNESPECTEDERROR = "An unexpected error occured.";
public String UnexpectedError {get{return UNESPECTEDERROR; }}
}
public class ControlsConst
{
private TopNavigationConst topNavigation = new TopNavigationConst();
public TopNavigationConst TopNavigation {get{return topNavigation;}}
}
public class GeneralConst
{
public ErrorsConst errors = new ErrorsConst();
public ErrorsConst Errors {get{return errors;}}
}
public class LabelsConst
{
public static ControlsConst controls = new ControlsConst();
public static GeneralConst general = new GeneralConst();
public ControlsConst Controls {get{return controls;}}
public GeneralConst General {get{return general;}}
}
public class Constants
{
public static LabelsConst labels = new LabelsConst();
public static LabelsConst Labels {get{return labels;}}
}
public class Test
{
public static void Main()
{
var value = Constants.Labels.Controls.TopNavigation.Save;
System.Console.WriteLine(value);
}
}
}
I know there are a lot of threads talking about this but so far I haven't found one that helps my situation directly. I have members of the class that I need to access from both static and non-static methods. But if the members are non-static, I can't seem to get to them from the static methods.
public class SomeCoolClass
{
public string Summary = "I'm telling you";
public void DoSomeMethod()
{
string myInterval = Summary + " this is what happened!";
}
public static void DoSomeOtherMethod()
{
string myInterval = Summary + " it didn't happen!";
}
}
public class MyMainClass
{
SomeCoolClass myCool = new SomeCoolClass();
myCool.DoSomeMethod();
SomeCoolClass.DoSomeOtherMethod();
}
How would you suggest I get Summary from either type of method?
How would you suggest I get Summary from either type of method?
You'll need to pass myCool to DoSomeOtherMethod - in which case you should make it an instance method to start with.
Fundamentally, if it needs the state of an instance of the type, why would you make it static?
You can't access instance members from a static method. The whole point of static methods is that they're not related to a class instance.
You simply can't do it that way. Static methods cannot access non static fields.
You can either make Summary static
public class SomeCoolClass
{
public static string Summary = "I'm telling you";
public void DoSomeMethod()
{
string myInterval = SomeCoolClass.Summary + " this is what happened!";
}
public static void DoSomeOtherMethod()
{
string myInterval = SomeCoolClass.Summary + " it didn't happen!";
}
}
Or you can pass an instance of SomeCoolClass to DoSomeOtherMethod and call Summary from the instance you just passed :
public class SomeCoolClass
{
public string Summary = "I'm telling you";
public void DoSomeMethod()
{
string myInterval = this.Summary + " this is what happened!";
}
public static void DoSomeOtherMethod(SomeCoolClass instance)
{
string myInterval = instance.Summary + " it didn't happen!";
}
}
Anyway I can't really see the goal you're trying to reach.