This question already has answers here:
How do I call a non-static method from a static method in C#?
(11 answers)
Closed 5 years ago.
I have a C# console app with a static main method.
I want to be able to call a non-static method in main but
cannot.
I believe I need to keep main static but I also want to
run non-static methods within the program?
The statement below says an object reference is required.
c1 = new Class1()
Where / how do I instantiate non-static objects in this program?
Thanks
namespace VER
{
class Example
{
private Dictionary<string, long> dStrLong;
Class1 c1;
static void Main(string[] args)
{
c1 = new Class1();
}
}
}
If you make Class1 c1 static, you will be able to assign new object to it and call its non-static method.
Alternatively, remove Class1 c1 field from the class and write Class1 c1 = new Class1();.
I think you need to understand how this works behind the scenes.
When you use a static method, a silent instance is created for you and that is the instance that serves the calls to static methods.
Anything that is not static, belongs to each and every instance you create. That is why the compiler is saying an object reference is required (c1 is declared as an instance member).
In order for you to consume c1 within main, you can either make it static as well or make it a public member and create an instance so you can use it:
namespace VER
{
class Example
{
private Dictionary<string, long> dStrLong;
//You can make it static
static Class1 c1 = new Class1();
static void Main(string[] args)
{
c1.DoSomething();
}
}
}
OR
namespace VER
{
class Example
{
private Dictionary<string, long> dStrLong;
//You can make it public
public Class1 c1 = new Class1();
static void Main(string[] args)
{
var c1 = new Example();
c1.DoSomething();
}
}
}
As your code currently exists, you are trying to access a variable that belongs to an instance from a static method.
Either way, make sure you instantiate an object for the variable.
Related
This is probably something really basic, but I'm not sure what's wrong:
partial class Program {
static void Main(string[] args) {
ADAttributes allObjectAttributes = new ADAttributes("AllObjects");
}
static void calcs() {
var x = allObjectAttributes; // <--- Name does not exist in the current context
}
}
Why is the calcs() method unable to see allObjectAttributes that was created in Main()?
Because C# does not work that way. The scope of the variable allObjectAttribute is to the Main-method, only in that method is the variable visible/usable.
If you want to have access to the variable from another method, you have to create a class field, and in your case, a static one.
This question already has answers here:
C# static class constructor
(7 answers)
What is the use of static constructors?
(8 answers)
Closed 5 years ago.
In my class there are several methods with the following signature:
public static void SomeMethod()
{
...
}
Most of these methods depend on the value of the private static field.
It is necessary that the caller had any way to assign a value to this field before calling any of these static methods.
I want to have a single Random object for use by all classes in the application. How do I pass a reference to this object to use it in the static methods of another class?
I have a private static field in the class with static methods and a static initializer:
public static void Init(Random random)
{
_random = random;
}
But how to make sure that the initializer was called? To do the check and throw exceptions in every method, it seems to me redundant. There may be another option.
Finally I found an acceptable solution for me:
Define public static property in the class that contains application entry point:public static Random Rnd { get; } = new Random();
Define private static Random _random in other classes;
Implement a static constructor for other classes that includes this code:
Type type = Assembly.GetExecutingAssembly().EntryPoint.DeclaringType;
var randomTypeProperties =
type.GetProperties().Where(p => p.PropertyType == typeof(Random));
foreach (var propertyInfo in randomTypeProperties)
{
_random = (Random)propertyInfo.GetValue(null);
}
I can mark a message from #Andy as the answer, because it is after all a static constructor.
Thank you to everyone who took part in the discussion.
It's never too late to learn. Yesterday, as I read about the design patterns, I realized that the Singlton is exactly what I needed:
public sealed class RandomAsSingleton : Random
{
private static volatile RandomAsSingleton _instance;
private static readonly object _syncRoot = new object();
private RandomAsSingleton() { }
public static RandomAsSingleton Instance
{
get
{
lock (_syncRoot)
{
if (ReferenceEquals(_instance, null)) { _instance = new RandomAsSingleton(); }
return _instance;
}
}
}
}
My previous solution seems to me a little bit ugly right now.
You might want to use a static constructor
// Static constructor is called at most one time, before any
// instance constructor is invoked or member is accessed.
static SimpleClass()
{
// set your private static field
}
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
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);
}
I have searched about static variables in C#, but I am still not getting what its use is. Also, if I try to declare the variable inside the method it will not give me the permission to do this. Why?
I have seen some examples about the static variables. I've seen that we don't need to create an instance of the class to access the variable, but that is not enough to understand what its use is and when to use it.
Second thing
class Book
{
public static int myInt = 0;
}
public class Exercise
{
static void Main()
{
Book book = new Book();
Console.WriteLine(book.myInt); // Shows error. Why does it show me error?
// Can't I access the static variable
// by making the instance of a class?
Console.ReadKey();
}
}
A static variable shares the value of it among all instances of the class.
Example without declaring it static:
public class Variable
{
public int i = 5;
public void test()
{
i = i + 5;
Console.WriteLine(i);
}
}
public class Exercise
{
static void Main()
{
Variable var1 = new Variable();
var1.test();
Variable var2 = new Variable();
var2.test();
Console.ReadKey();
}
}
Explanation: If you look at the above example, I just declare the int variable. When I run this code the output will be 10 and 10. Its simple.
Now let's look at the static variable here; I am declaring the variable as a static.
Example with static variable:
public class Variable
{
public static int i = 5;
public void test()
{
i = i + 5;
Console.WriteLine(i);
}
}
public class Exercise
{
static void Main()
{
Variable var1 = new Variable();
var1.test();
Variable var2 = new Variable();
var2.test();
Console.ReadKey();
}
}
Now when I run above code, the output will be 10 and 15. So the static variable value is shared among all instances of that class.
C# doesn't support static local variables (that is, variables that are declared in method scope).
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members#static-members
You can declare static fields (class members) though.
Reasoning: Static field is a state, shared with all instances of particular type. Hence, the scope of the static field is entire type. That's why you can't declare static instance variable (within a method) - method is a scope itself, and items declared in a method must be inaccessible over the method's border.
static variables are used when only one copy of the variable is required. so if you declare variable inside the method there is no use of such variable it's become local to function only..
example of static is
class myclass
{
public static int a = 0;
}
Variables declared static are commonly shared across all instances of a class.
Variables declared static are commonly shared across all instances of a class. When you create multiple instances of VariableTest class This variable permanent is shared across all of them. Thus, at any given point of time, there will be only one string value contained in the permanent variable.
Since there is only one copy of the variable available for all instances, the code this.permament will result in compilation errors because it can be recalled that this.variablename refers to the instance variable name. Thus, static variables are to be accessed directly, as indicated in the code.
Some "real world" examples for static variables:
building a class where you can reach hardcoded values for your application. Similar to an enumeration, but with more flexibility on the datatype.
public static class Enemies
{
public readonly static Guid Orc = new Guid("{937C145C-D432-4DE2-A08D-6AC6E7F2732C}");
}
The widely known singleton, this allows to control to have exactly one instance of a class. This is very useful if you want access to it in your whole application, but not pass it to every class just to allow this class to use it.
public sealed class TextureManager
{
private TextureManager() {}
public string LoadTexture(string aPath);
private static TextureManager sInstance = new TextureManager();
public static TextureManager Instance
{
get { return sInstance; }
}
}
and this is how you would call the texturemanager
TextureManager.Instance.LoadTexture("myImage.png");
About your last question:
You are refering to compiler error CS0176. I tried to find more infor about that, but could only find what the msdn had to say about it:
A static method, field, property, or event is callable on a class even
when no instance of the class has been created. If any instances of
the class are created, they cannot be used to access the static
member. Only one copy of static fields and events exists, and static
methods and properties can only access static fields and static
events.
Static variables are used when only one copy of it is required. Let me explain this with an example:
class circle
{
public float _PI =3.14F;
public int Radius;
public funtionArea(int radius)
{
return this.radius * this._PI
}
}
class program
{
public static void main()
{
Circle c1 = new Cirle();
float area1 = c1.functionRaduis(5);
Circle c2 = new Cirle();
float area2 = c1.functionRaduis(6);
}
}
Now here we have created 2 instances for our class circle , i.e 2 sets of copies of _PI along with other variables are created. So say if we have lots of instances of this class multiple copies of _PI will be created occupying memory. So in such cases it is better to make such variables like _PI static and operate on them.
class circle
{
static float _PI =3.14F;
public int Radius;
public funtionArea(int radius)
{
return this.radius * Circle._PI
}
}
class program
{
public static void main()
{
Circle c1 = new Cirle();
float area1 = c1.functionRaduis(5);
Circle c2 = new Cirle();
float area2 = c1.functionRaduis(6);
}
}
Now no matter how many instances are made for the class circle , only one copy exists of variable _PI saving our memory.
Static classes don't require you to create an object of that class/instantiate them, you can prefix the C# keyword static in front of the class name, to make it static.
Remember: we're not instantiating the Console class, String class, Array Class.
class Book
{
public static int myInt = 0;
}
public class Exercise
{
static void Main()
{
Book book = new Book();
//Use the class name directly to call the property myInt,
//don't use the object to access the value of property myInt
Console.WriteLine(Book.myInt);
Console.ReadKey();
}
}
The data members and function members that operate on the instance of the type
are called instance members. The int’s ToString method (for example) are examples of instance members. By default, members are instance members.
Data members and function members that don’t operate on the instance of the type, but rather on the type itself, must be marked as static. The Test.Main and Console.WriteLine methods are static methods. The Console class is actually a static class, which means all its members are static. You never actually create instances of a Console—one console is shared across the whole application.
In response to the "when to use it?" question:
I often use a static (class) variable to assign a unique instance ID to every instance of a class. I use the same code in every class, it is very simple:
//Instance ID ----------------------------------------
// Class variable holding the last assigned IID
private static int xID = 0;
// Lock to make threadsafe (can omit if single-threaded)
private static object xIDLock = new object();
// Private class method to return the next unique IID
// - accessible only to instances of the class
private static int NextIID()
{
lock (xIDLock) { return ++xID; }
}
// Public class method to report the last IID used
// (i.e. the number of instances created)
public static int LastIID() { return xID; }
// Instance readonly property containing the unique instance ID
public readonly int IID = NextIID();
//-----------------------------------------------------
This illustrates a couple of points about static variables and methods:
Static variables and methods are associated with the class, not any specific instance of the class.
A static method can be called in the constructor of an instance - in this case, the static method NextIID is used to initialize the readonly property IID, which is the unique ID for this instance.
I find this useful because I develop applications in which swarms of objects are used and it is good to be able to track how many have been created, and to track/query individual instances.
I also use class variables to track things like totals and averages of properties of the instances which can be reported in real time. I think the class is a good place to keep summary information about all the instances of the class.
Try calling it directly with class name Book.myInt
On comparison with session variables, static variables will have same value for all users considering i am using an application that is deployed in server. If two users accessing the same page of an application then the static variable will hold the latest value and the same value will be supplied to both the users unlike session variables that is different for each user. So, if you want something common and same for all users including the values that are supposed to be used along the application code then only use static.
You don't need to instantiate an object, because yau are going to use
a static variable:
Console.WriteLine(Book.myInt);
Static variable retains it's previous value until the program exit. Static is used by calling directly class_Name.Method() or class_Name.Property. No object reference is needed. The most popular use of static is C#'s Math class.
Math.Sin(), Math.Cos(), Math.Sqrt().
I am new to C# and visual studio 2005
I created a new Console Application project in VS2005 and added a Class1.cs file to the existing Program.cs file that was created by default.
The Class1.cs file has the following simple code:
public class Class1
{
public Class1()
{
}
~Class1()
{
}
public void PrintMessage()
{
Console.WriteLine("\nHello\n");
Console.Read();
}
}
And program.cs file has the following:
class Program
{
static void Main(string[] args)
{
PrintMessage();
}
}
When I try to compile I get the following error:
The name 'PrintMessage' does not exist in the current context.
Any help?
Thanks, Viren
Try:
Class1 myClass = new Class1();
myClass.PrintMessage();
Or, what might be better since this seems like a utility function. Change your method definition to:
public static void PrintMessage()
So you can call it directly.
Class1.PrintMessage();
The name 'PrintMessage' does not exist in the current context.
It exists in another context - that of class Class1. Since it is a public function of that (public) class, you can use it, by creating an instance of Class1 (the PrintMessage function is not static, so you need an instance of Class1 to call it) and then invoking the PrintMessage function on it.
class Program
{
static void Main(string[] args)
{
Class1 someClass1Object = new Class1();
someClass1Object.PrintMessage();
}
}
PrintMessage is not a method of the class "Program", it's a method of Class1. Try
Class1 c = new Class1();
c.PrintMessage();
You probably also want to go through a tutorial or two :)
class Program
{
static void Main(string[] args)
{
new Class1().PrintMessage();
}
}
or make PrintMessage() to be static so you can use it next way:
public class Class1
{
public static void PrintMessage()
{
// ..
}
}
class Program
{
static void Main(string[] args)
{
Class1.PrintMessage();
}
}
You need a reference to the class where the method is. You must do that with:
Class1.PrintMessages();
Since Class1 is not static, you also need an instance of that class. You could do that with:
Class1 c = new Class1();
Finally, you have to call the method prefixed with the instance variable. Your code will look something like this:
Class1 c = new Class1();
c.PrintMessages();
If you want, you can shorten this code with the sentence
new Class1().PrintMessages();
that do the same as before.
Calling PrintMessage() inside of your Main function (which is a function on the Program class) means that the compiler is going to look for a function called PrintMessage() somewhere in the program class.
What you have is called an instance function on the Class1 class. In order to call this type of function, you need an instance of Class1 in your function. Something like this:
static void Main(string[] args)
{
Class1 myClass = new Class1();
myClass.PrintMessage();
}
Making the method static is probably what you want, rather than the other suggestions here:
public static void PrintMessage()
{
Console.WriteLine("\nHello\n");
Console.Read();
}
static tells the compiler that this method doesn't depend on an instance of a class. If that doesn't mean anything to you, read up on the topic of classes in your favourite C# book.
You need a reference to the Class1 class in order to call a method of the class. Try:
Class1 myClass = new Class1();
myClass.PrintMessage();
Your PrintMessage() method is a method of the Class1 class. You have to reference that class to get to the method.
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1(); //Create an instance of your class
c.PrintMessage(); //Call the PrintMessage method of class Class1
}
}
Note: You may want to rename Class1 to something more descriptive.
Print message is not a part of Main:
u have to tell it where it is:
Class1 messageClass = new Class1();
messageClass.PrintMessage();
you need to reference the class that print message . . . AKA: Class1.PrintMessage()