Converting to int from string in public static [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
private class global
{
public static string str = label4.Text;
int a = Convert.ToInt32(str);
}
private void button8_Click(object sender, EventArgs e)
{
string myString = label4.Text;
int Val = Int32.Parse(myString);
dataGridView1.Rows.Add(label2.Text, Val * global.a );
}
Hello guys I have some problem here, then I convert string to int in private void it works fine, but then I try to convert it on public global it shows errors, any ideas how to fix it?
DB2.Form2.global.a' is inaccessible due to its protection level
An object reference is required for the non-static field, method, or property 'DB2.Form2.global.a
An object reference is required for the non-static field, method, or property 'DB2.Form2.label4

a is not visible outside the class global, you should make it public:
public int a = Convert.ToInt32(str);
Since the global class is not marked as static you either make it static or create an instance of global.
private static class global
{
public static int a = ...
}
or when not making it static (but a must be public):
var myGlobal = new global();
int x = myGlobal.a;
Furthermore:
classes should be capitalized
public class Global { ... }
Same goes for public properties/fields:
public int A = 1;
public string Str = "";

a is not defined as a global static variable.
Redefine it as public static int a;

You can't access a field from a class without first instantiating an object unless that field is static and the field is accessible.

your int is private int your global class.
Change it to public and static.

a is not static and public. So either make it public static or instantiate the class and use the instance to access a.
private field can't be accessed outside of class.

variable a is private and hence not accessible outside the class and moreover it's declared as instance member and not static member.
you need to declare it as public static int a based on your posted code usage
Your class definition should look like
private class global
{
public static string str = label4.Text;
public static int a;
a = Convert.ToInt32(str);
}
First error is inaccessible due to its protection level cause because you declared a as private.
second error An object reference is required for the non-static field, method, or property caused because you were trying to access an instance member as static member.

Related

How to change variable from one class using another in C# [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
The title may sound a bit confuse, but what I want to do is basicaly create a class,
declare a public int with the default value of 0, then inside the Program class I
permanently change the value of this variable in a function, and if I print this value using another function, it will print the value set in the first function.
For example:
using System;
{
class Global
{
public int variable = 0;
}
class Program
{
static void Main(string[] args)
{
Global test = new Global();
test.variable = 10;
//it makes no sense in this code to use another function,
//but in my other project it does
Function();
Console.ReadLine();
}
static void Function()
{
Global test = new Global();
//should print 10
Console.WriteLine(test.variable);
}
}
}
You could create a static class if you don't want to bother with injection like this:
public static class Global
{
public int variable = 0;
}
class Program
{
static void Main(string[] args)
{
Global.variable = 10;
}
static void Function()
{
Console.WriteLine(Global.variable);
}
}
or you could just inject the class through as a parameter from wherever you call it.
public class Global
{
public int variable = 0;
}
class Program
{
static void Main(string[] args)
{
var test = new Global();
test.variable = 10;
}
static void Function(Global global)
{
Console.WriteLine(global.variable);
}
}
If you want to permanently change this variable inside every class you could use a static class, but then you wouldn't be able to create instances of it (if you wanted other variables to be non-static.
I would recommend looking into IServiceProviders because they can be really useful if the Function() method is inside another class and you want to pass through the Global class.

Is it possible to assign to a (public or private) class member an initial value using a static method from another class?

say I have the following class
public class MyClass1 {
protected static int MyIntName1 = 0;
public static int GetMyIntName1() {
return MyIntName1;
}
public void MyMethod1() {
MyIntName1 += 1;
}
}
I then have a second class which has a private static int member for which I want to assign as initial value the value of MyIntName1 of the first class. Is there a way to do that ? Does the fact of being private or public make any difference actually ? I tried to do the following
public class MyClass2 {
private static int MyIntName2 = MyClass1.GetMyIntName1(); /* Here the value of MyIntName2
is assigned 0 not matter which value MyIntName1 could have */
public void MyMethod2() {
MyIntName2 = MyClass1.GetMyIntName1(); /*If I do this then MyIntName2 gets
the value of MyIntName1 but that holds only in this method and I would have to
repeat this in any other method of this class that requires the value of MyIntName1...*/
}
}
but no value is assigned to MyIntName2. However, if I do the same inside of a method of the second class, the value of MyIntName1 is assigned but that would only hold in that particular method. To be honest, I am not even sure that what I am trying to achieve makes any sense since I already have a static method which I am trying to assign at declaration to another static member inside a different class. It may be that there is no real purpose in doing this as I could just use the getter method from MyClass1 wherever I need it... However, I am wondering which are all the possibilities of assigning an initial value to class member. Forgive me if the question has already been asked of this does not make any sense.
Thank you.

Is int b; declaration for an integer number or for a field ( and understandig the meaning of: "directly inside the class" ) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm looking for a differences between declarations to define an integer numbers and declarations for a fields.
EXAMPLE: Declaration 'int b;' can be declaration for the inetger number b or it can be the declaration for the private field b. As it looks like, it depends on where this declaration is situated.
I know, that typical declaration to define a field is 'private string field;'
In the code below in the class MyClass I can't declare the integer numbers, but just the fields. Why?
I wrote 'int b;' because I wanted to declare the integer number b, but I got the field b. Visual Studio shows me, that 'b' is the field.
using System;
class MyClass
{
int b;
public static int x = 20;
public static int y;
public static int z = 25;
public MyClass(int i)
{
x = i;
y = i;
z = i;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y, MyClass.z);
MyClass mc = new MyClass(25);
Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y, MyClass.z);
Console.ReadLine();
}
}
All fields are variables, but not all variables are fields.
From the documentation,
A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type.
Or, more simply, fields are variables that are associated only with the class or object itself, not with a specific method.
Thus, when you have int b = 7;, it is technically correct to call it a variable, but it's more specific to call it a field. It's the same way that it's technically correct to simply call a Porsche Boxter a car - it is, in fact, a car, but it's more descriptive (and, therefore, potentially more useful) to call it a Boxter.
Note in particular that the definition of a field says absolutely nothing about what else is included in the class. A field is a field regardless of what other content you do (or don't) have in the class (so, for example, the fact that MyClass doesn't have a Main method is completely irrelevant).
Fields can be distinguished from a local variable, which is declared inside a method and is associated only with that particular method. For example:
public class MyClass {
public int a = 10; // This is a field
int b = 20; // Also a field
public void MyMethod() {
int c = 30; // This is a local variable, NOT a field
}
}
Note, in particular, that c is not "declared directly in a class or struct" - it's declared inside a method. Thus, by definition it's not a field.
Based on the wording in your question, I feel that your understanding of using the words "variables" and "field" is misguided.
You seem to be calling:
"variables" as private fields
"fields" as public fields
Take a look at the below code block, to help:
class MyClass
{
int b = 7; // this is a private field
private int c = 8; // this is a private field
public int d = 10; // this is a public field
}
In addition, from the code above, you can now understand the reason why you are unable to access b. It is due to the private access modifier that is assumed. You need to change it to a public field.
So, what you'll want to get your code up and going quickly is change:
int b = 7;
to
public int b = 7;
and then you can change
public static void Main()
{
Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y, MyClass.z);
MyClass mc = new MyClass(25);
Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y, MyClass.z);
Console.ReadLine();
}
to
public static void Main()
{
Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y, MyClass.z);
MyClass mc = new MyClass(25);
Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y, MyClass.z);
Console.WriteLine("{0}", mc.b);
Console.ReadLine();
}
Take special note that public fields should usually be avoided in favor for properties, you can read more about that by doing a few searches online.
Additional Resources
Fields (C# Programming Guide)
static (C# Reference)
Static Classes and Static Class Members (C# Programming Guide)
Properties (C# Programming Guide)

C# A variable that cannot be changed outside of function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Is it possible to declare a variable inside a called function, and no external source can change this variable? For example:
private void SetVariable(){
privatetypevariable variable = "hello";
}
variable = "world"; //<-- doesnt work because it cannot access the variable 'variable' inside SetVariable()
How do I access the variable outside of the scope of the above method?
Instead of declaring the variable in the method define it as a class field. Then you can change it from anywhere inside the class. Fields are generally marked as private so it cannot be changed outside the class. If you want to expose it outside the class use a property instead with a public type.
private privatetype fielda;
void methodA(){
fielda = "hello";
}
void someOtherMethod()
{
fielda = fielda + " world";
}
It wouldn't be possible due to the fact that a variable only lives inside its given scope, as soon as you exit the scope, the variable is lost.
To add to that, you can't add visibility modifiers to your variables declared in a method
The below code won't work since s only lives in the scope of methodA() and is lost as soon as you exit the scope.
private void methodA(){
String s = "hello";
}
private void methodB(){
s = s + " world"; //even tho methodA created an s variable, it doesn't exist in the eyes of methodB
}
You could do something as follows:
class someClass{
private String s;
public someClass(){
s = "hello world";
}
public String getVariable(){ //you can read this variable, but you can't set it outside of this class.
return s;
}
}
If you specify a variable inside a function, it is scoped to only that function in C#.
Example 1:
private void foo(string bar)
{
string snark = "123";
}
private void derk()
{
snark = "456";
}
Example 1 would cause a compile error. If you mean inside a class, declare the property as readonly and it cannot be changed outside of it's initial constructor.
Example 2:
public class Lassy
{
private readonly string _collarColour;
public Lassy(string collarColour)
{
_collarColour = collarColour;
}
private void SetCollarColour(string newColour)
{
_collarColour = newColour;
}
}
Example 2 will also cause a compile error because you cannot assign to a readonly attribute in a class outside of it's initial constructor.
To achieve what you want, use readonly.

I can access private members in a copy ctor in C# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why and how does C# allow accessing private variables outside the class itself when it’s within the same containing class?
This has completely passed me by some how, apparently the code below is legal, and more surprising is legal from framework 2 onwards...
public class Magic
{
private readonly int _anInt;
private readonly string _aString;
public Magic(int anInt, string aString)
{
_anInt = anInt;
_aString = aString;
}
public Magic(Magic toCopy)
{
_anInt = toCopy._anInt; // Legal!
_aString = toCopy._aString; // Legal!
}
public void DoesntWorkMagic(Magic toCopy)
{
_anInt = toCopy._anInt; // edit: Will work if not readonly.
_aString = toCopy._aString;
}
public int AnInt { get { return _anInt; } }
public string AString { get { return _aString; } }
}
What's going on? I've seen so many copy constructors doing excess work over the years, I wouldn't have believed this work until I came across it. Are there any caveats to its use (besides the obvious threading issues)?
private is not object level, it is class level, so objects of the same class know about their private aspects, so are allowed to change private things on other object of the same class.
private prevents other types poking around where they shouldn't go.
There is no "copy constructor" in C#. There are only constructors.
In your code you have the argument toCopy that is a instance of the current class Magic. So as it is the same class you can access the private fields toCopy._anInt and toCopy._aString (it is a modifier that makes the field visible all the instances of the same class).
And as you are in a constructor, you can set the fields _anInt, _aString of the new instance.
The readonly keyword just say: "this field can only be set in the constructor of the instance.

Categories

Resources