C# class variable initialization - c#

I want to declare and initialize a string variable that is local to a class but can be accessed by all functions of the class. Fyi, this is an app for a gui which will be making use of several text files in folders. I am trying to set a string variable containing the project directory path so it can be accessed by all the functions within this class.
I have provided an portion of my code including the function that sets the path along with a function that uses the string variable when set.
public class Program
{
private string DirectoryPath;
public static void Main()
{
setPaths();
SetGroundTempArray();
}
public static void setPaths()
{
DirectoryPath = Directory.GetCurrentDirectory();
}
public static void SetGroundTempArray()
{
string groundtempfile = "\\groundtemp.txt";
string groundtempdir = "\\Text Files";
string groundtempFP = DirectoryPath + groundtempdir + groundtempfile;
}
}

Your code won't compile.
You should declare the DirectoryPath class field as static:
private static string DirectoryPath;

So you are currently on the right track. In C# we call them Fields
Fields typically store the data that must be accessible to more than
one class method and must be stored for longer than the lifetime of
any single method
In your case private string DirectoryPath; is a field. And you are following the good practice of making it private.
Also as noted you have all methods as static so you need to make the Field variable static as well to access it
private static string DirectoryPath;
A field can optionally be declared static. This makes the field
available to callers at any time, even if no instance of the class
exists.

As given in your example, you have done it right as the functionality you want. But you may need to learn more about the usage of static keywords in C#. You can learn more about it at MSDN
Here's a intercept about your code, that might clear your concept.
As DirectoryPath is used by a static method in your progream, you must need to declare this variable as static also because of, setPaths method is used in static Main, and Main is the topmost level static class that don't requires the instance to be created of the Program Class. and that is why, Main method would require all the methods or variable or fields is being used inside the method must be declared as static.
public class Program
{
private static string DirectoryPath;
public static void Main()
{
setPaths();
SetGroundTempArray();
}
public static void setPaths()
{
DirectoryPath = Directory.GetCurrentDirectory();
}
public static void SetGroundTempArray()
{
string groundtempfile = "\\groundtemp.txt";
string groundtempdir = "\\Text Files";
string groundtempFP = DirectoryPath + groundtempdir + groundtempfile;
}
}

Add static in front of string.
class Program
{
//add static in front of string
static String a = "Hello";
static void Main(string[] args)
{
h();
Console.ReadKey();
}
public static void h()
{
Console.WriteLine(a);
}
}

Related

The name does not exist in the current context?

I'm a total noob in c#, since today. I couldn't find a good tutorial or anything, that could solve this obviously dumb problem. Basically, I try to translate a program from Python to C#. Normally in Python I define constants in the constructor. Where the hell should I put them in c#? I tried to put them in the constructor then I put them in Main(), because there was this error. But the error persists.
static void Main(string[] args)
{
var _top = 0
...
}
public string[] topToken()
{
if (_top < _tokens.Count())
{ return _tokens[_top];}
_top is declared inside Main, so it's not going to have visibility inside the topToken method. It's a local variable, scoped only to Main.
To give your variables visibility for the entire class, you need to declare them outside of any method.
Ex:
public class SomeClass
{
public int someVariable; // all methods in SomeClass can see this
public void DoIt() {
// we can use someVariable here
}
}
Note, by makeing someVariable public, it also means other we can access it directly. For example:
SomeClass x = new SomeClass();
x.someVariable = 42;
If you want to prevent this and only allow the methods/properties/etc. of the class to be able to see the someVariable variable, you can declare it as private.
In cases where you need a public variable, it's usually best to declare it like this (this is an example of an auto-implemented property):
public class SomeClass
{
public int SomeVariable { get; set; }
public void DoIt() {
// we can use SomeVariable here
}
}
This uses
if you want _top to be available outside of the Main method, place it here:
int _top = 0; //here instead
static void Main(string[] args)
{
...
}
public string[] topToken()
{
if (_top < _tokens.Count())
{ return _tokens[_top];}
}
Change your code to this:
const int _top = 0;
static void Main(string[] args)
{
...
}
public string[] topToken()
{
if (_top < _tokens.Count())
{ return _tokens[_top];}
To make _top accessible throughout your class you have to declare it as a field or a constant. A field requires actual storage while a constant is simply replaced by the actual value by the compiler. As you described _top as a constant I decided to declare it as such.
If you need a field and not a constant you have to declare it static because it is accessed in a static method:
static int _top = 0;
Because there is no public or protected in the declaration of _top it is private to the class. If you prefer you can add private in front of the declaration but that will be the default if the visibility is missing.

how to define a Global Structure in C#?

I want to define a global structure in C# and use it in three separate subroutines. I have already created the structure but I don't know how to make it a global variable so I can use it in multiple sections of my code. Any help is appreciated.
public struct Simple
{
public int Position;
public bool Exists;
public double LastValue;
};
static void Main(string[] args)
{
Simple s;
s.Position = 1;
s.Exists = false;
s.LastValue = 5.5;
}
So I want to use a Simple structure in two other routines in my code and possible pass it to different form (multiple usage of one variable).
The closest thing to "global" in C# is "static". Simply define the class and all members as static and it'll be accessible from anywhere the containing namespace is referenced. EDIT as Servy correctly points out, the class itself does not have to be static; however doing so forces all members to be static at compile-time. Also, static members can have any visibility, so you can have a private static field used by a public static property or method, and you can have an internal static class that won't be visible outside its home assembly. Just being static doesn't automatically make it wide open.
However, a better pattern might be the Singleton; you define a class that has one static instance of itself, that can then be passed around. The benefit is that you can still deal with the object as an instance class if you want to, but the same instance is available everywhere using a static getter. Here's some reading material: http://csharpindepth.com/Articles/General/Singleton.aspx
In your case it appears that you have a object as a local variable in your main method that you need to use in another method. The appropriate solution in this context is to add a parameter to that other method. Take a look at this example:
public class MyObject
{
public int Value;
}
public static void Main(string[] args)
{
MyObject obj = new MyObject();
obj.Value = 42;
PrintObject(obj);
Console.WriteLine("Press any key to exit...");
Console.ReadKey(true);
}
public static void PrintObject(MyObject obj)
{
Console.WriteLine(obj.Value);
}

Implementation Problem with Static Sealed Class

I have a Sealed class in C#, which already exists and all methods are static.
It does some file operations with xml file. The file name till today was hardcoded into source.
Now the requirement needs to keep it in Configuration file.
The problem is:
Since class is extract, i need to expose some static 'Initialize' method to assign filename to some local static filename variable, which will replace hardcoded string.
So, i always have to make sure, Initialize is called first and then later method.
So, the better way is to have constructor, which i cant write.
I want a better way to do this ensuring type safety.
If the filename field is static, you could make it a property or method and make sure the getter does the work of initializing it from the configuration file if it is not already initialized...
That way you don't have to explicitly initialize the class via a method you can have the access to the property itself initialize the value.
Something like below..
static string FileName { get { return (_field ?? _field = GetFileName()); } }
static string GetFileName() { /* TODO: Return filename from config */ }
Why can't you use a static constructor?
You could write a static constructor to initialize your paths before the static members are referenced.
More info can be found here
If the class itself doesn't know how to access the config I'd use a one time setter:
private static string _filename;
public static string Filename
{
get
{
if(_filename==null)
throw new InvalidOperationException("Filename not set");
return _filename;
}
set
{
if(_filename!=null)
throw new InvalidOperationException("Filename set twice");
_filename=value;
}
}
Or if the class can access the config directly it's even easier:
private static readonly string Filename;
static MyClassName()
{
Filename=GetFilenameFromConfig();
}
Just initialize it in a static constructor.
Assuming the configuration file path is known (i.e. the class takes no formal arguments), then a static constructor might help.
You could change your current class from something like:-
public static Foo
{
public static void Execute()
{
const string FileName = "foo.xml";
// ...
}
}
To something like
public static Foo
{
public static void Execute()
{
Execute("foo.xml");
}
public static void Execute(string fileName)
{
// ...
}
}
Current clients of the code can continue to use the original method (hard coded file name) and any new clients which have the file name as a configuration item can use the new method which takes the file name as a parameter. Or, if you have decided that all client should use the new method, then you can change them to do that and remove the old method.
The simplest option would be to add a static constructor. That will be executed before any other code:
public static class Foo
{
static Foo()
{
// Initialization code
}
// Other methods which can depend on initialization code having run
}
As I say, this is the simplest - in terms of changes to your existing code. However, code like this tends to be hard to debug, and if you have a lot of static constructors which depend on each other, you can get into some tricky situations (particularly if you have cyclic dependencies). For an example of this, watch the "C# Puzzlers" video from NDC 2010 - an excellent talk given by Eric Lippert and Neal Gafter.

How I will use the following static variable from other class?

I have a class like following:
public class Trainee
{
private static int numberOfTrainee = 30;
private string traineeName;
private string tarineeId;
}
Now I want to access the static data "numberOfTrainee" in the following class without creating a object of "Trainee" class and I don't want to write getter for "numberOfTrainee". Because, static member can be used only using "." operator.
public class TraineeUI : Form
{
private void showButton_Click(object sender, EventArgs e)
{
// I want to access "numberOfTrainee" here. Something like following:
// MessageBox.Show("Total number of trainee is: " );
}
}
If you don't want a getter for it, the only way to use it from elsewhere will be to increase the visibility, like so:
public class Trainee
{
public static int NumberOfTrainee = 30;
private string traineeName;
private string tarineeId;
}
// Other code.
MessageBox.Show("Total number of trainee is: " + Trainee.NumberOfTrainee);
However, I would recommend against doing this with a field that can change. Unless it's a constant, you should define a property to control access to this field, static or not.
You should make a property, like this:
public class Trainee
{
private static int numberOfTrainee = 30;
public int TraineeCount { get { return numberOfTrainee; } }
private string traineeName;
private string tarineeId;
}
Note that you may want to consider thread safety... it's possible that this simple implementation will give stale results in a multi-threaded environment. Making numberOfTrainee volatile would solve this.
Further, note that by making this a property rather than giving direct access to the field, you:
Can add extra logic should you ever wish to
Can make the property readonly, but modify the field from within the class
Keep encapsulation intact: a property is part of the API of a class, whereas a field is an implementation detail
I don't want to recycle what others have said, but....
You need to look at access modifiers. You say you don't want to make numberOfTrainee public, but you can make it internal. That way, if Trainee and TraineeUI are in the same assembly, than TraineeUI can access the field of Trainee without the field being exposed to types outside the assembly.
I would make it a property instead of a field though.
Well, either you could make it public and then just calll it with:
Trainee.numberOfTrainee
Or you could create a static readonly property.
public static int NumberOfTrainee
{
get
{
return numberOfTrainee;
}
}

call a function in utility class

I have a function in a utility class
namespace GUI.code
{
public class Utility
{
public string GetFileName(string grpID)
{
string filenameUNC = "\\\\" + "localhost" + "\\AgentShare\\";
string realPath = GetPath(filenameUNC);
return realPath;
}
}
}
now i call this function from another page in the project like this:
new utility.GetCSFileName(ID);
why do i need to add new, why cant i call it like
GetCSFileName(ID);
when i have
using GUI.code;
on top
if i remove new i get this error
Error 1 An object reference is required for the non-static field, method, or property 'copiunGUI.code.GUIUtility.GetCSFileName(string)
any suggestions
You can call Utility.GetFileName() if you change the declaration to public static string GetFileName(string grpID)
static means that the member is shared among all instances of the Utility class. Remember, c# is an object-oriented language. Non-static members are called instance members, and must be called on a distinct instance of the class. Each time you call new Utility(), you are creating such an instance, and this is distinct from every other.
This is useful when each instance of a class needs to maintain information (state) internally. If, however, a particular member does not use state data -- it accepts parameters, does work, and optionally returns a result -- it can be declared static. Then you call it not from the instance variable but from the class name itself (in this case Utility.GetFileName().
When all of the members of a class are static, you can add static to the class declaration itself. At that point, you would never be able to call new Utility(), which might be what you want in this case.
You need to mark your method as static.
public class Utility
{
public static string GetFileName(string grpID)
{
string filenameUNC = "\\\\" + "localhost" + "\\AgentShare\\";
string realPath = GetPath(filenameUNC);
return realPath;
}
}
You will then be able to call your method with Utility.GetFileName(...)
Read more on static methods / classes here.
It looks like you want to mark your method (and possibly your class also) as static:
public static class Utility
{
public static string GetFileName(string grpID)
...
Then you can call it like this:
string filename = Utility.GetFileName(ID);
Make the method static and you can use it without an instance of the class
eg
public static string GetFileName(string grpID)
usage:
Utility.GetCSFileName(ID);
You don't have to have a new one, if you set up your method as a static method:
public static string GetFileName(string grpID)
{
//your code here
}
Then you still have to call the Class name, but you don't have to instantiate it:
so instead of:
Utility util = new Utility();
util.GetFileName("myString");
you can do:
Utility.GetFileName("myString");
And the reason you can't do just GetFileName("myString") is that you're not calling it from inside the class where it's defined.
When a method is marked with the static keyword it means that you don't have to create a new instance of the object (using 'new') to call the method, as you intend.
One thing to watch out for is that if you mark a method as being static, it cannot call any non-static methods, only static ones. You also can't use any properties of the object that are non-static.
the trick is to define method as static. This will do it:
namespace GUI.code
{
public class Utility
{
public static string GetFileName(string grpID)
{
string filenameUNC = "\\\\" + "localhost" + "\\AgentShare\\";
string realPath = GetPath(filenameUNC);
return realPath;
}
}
}
now you can write utility.GetCSFileName(ID);.
But you still have to mention class.

Categories