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.
Related
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 2 years ago.
Improve this question
I already checked the link "Why can't I set “this” to a value in C#?" and I know that this is read-only. In other words, it (the content) cannot be assigned to another new object. I am just wondering that the philosophy or the consideration of this constraint in C#. If the reason is about to the safety of memory management, C# employs garbage collector and the usage in the future to an object would be determined.
public class TestClass
{
private int Number;
public TestClass()
{
this.Number = 0;
}
public TestClass(TestClass NewTestClass)
{
this = NewTestClass; // CS1604 Cannot assign to 'this' because it is read-only
}
}
As the result, it seems that the members needs to be updated one by one.
public TestClass(TestClass NewTestClass)
{
this.Number = NewTestClass.Number; // Update members one by one.
}
Any comments are welcome.
Note: For clarifying, the C++ part has been removed.
I don't think you are quite familiar with what dereferencing a pointer is.
Let's look at this method:
void TestClass::SetThisTest() {
*this = TestClass(this->IncreaseNumber().GetNumber()); // Assign new object to *this
}
You believe you are replacing the this, but you aren't. You are replacing the contents pointed to by this. Huge difference. *this != this.
Try this:
void TestClass::SetThisTest() {
std::cout << "this' address is " << std::to_address(this) << std::endl;
*this = TestClass(this->IncreaseNumber().GetNumber()); // shallow copy!
std::cout << "Now this' address is " << std::to_address(this) << std::endl;
}
The address doesn't change, but, the values this points do does. You are invoking (in this case) default shallow copy.
You can do this in C# very easily, you just aren't allowed to be that direct about it.
Here is the C# equivalent of your C++ class:
public sealed class ThisTest
{
private int _myNumber;
public ThisTest() { }
public ThisTest(int number) { _myNumber = number; }
public static void ShallowCopy(ThisTest to, ThisTest from)
{
to._myNumber = from._myNumber;
}
public int GetNumber() => _myNumber;
public ThisTest IncreaseNumber()
{
_myNumber += 1;
return this;
}
public void SetThisTest()
{
ShallowCopy(this, new ThisTest(this.IncreaseNumber().GetNumber()));
}
}
Because "this" is a reference to the object you instantiated that is only accessible from the object itself.
Why would "this" need to be anything but self-referential?
var s = new Sample { Title = "My Sample" };
//in this case, I want to see a string representation of "s"
Debug.WriteLine(s.ToString());
//in this case, we might want a copy
var s2 = (Sample)s.MemberwiseClone();
public class Sample
{
public string Title { get; set; }
public override string ToString()
{
//it wouldn't make sense to reference another object's "Title", would it?
return this.Title;
}
}
Is a "keyword" in C# used to refer the current instance of the class.
You can't assign a value to keyword, another example is keyword "base" and we can't assign a value. E.g. base = "text".
We can assign a value to an object through another class that contains the first.
public class TestClassParent
{
private TestClass _testObject;
public TestClassParent(TestClass testOject)
{
this._testObject = testObject;
}
}
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 6 years ago.
Improve this question
namespace SnakesAndLadders
{
class Node
{
int snakeHead ; // points to another node where the player goes down to
int ladderFoot; // points to another node where to player goes up to
}
class Program
{
Node[] gameBoard = new Node[100];
void loadStructure()
{
// first, set all the snakeheads and ladderFoots to zero
for (int i =0; i < 100; i++)
{
gameBoard[i].snakeHead = 0;
gameBoard[i].ladderFoot = 0;
}
}
static void Main(string[] args)
{
}
}
In C#, this won't work. For gameBoard[i], intellisense does not show it has a component of snakehead.
In C# fields of a class are private by default
class Node
{
public int snakeHead ; // points to another node where the player goes down to
public int ladderFoot; // points to another node where to player goes up to
}
Just making your fields public should fix your issue.
EDIT: using best practices you would keep fields private, but create properties and use them to deal with your data. Also naming private with an underscore is a common practice:
class Node
{
private int _snakeHead ; // points to another node where the player goes down to
public int SnakeHead
{
get {return _snakeHead;}
set {_snakeHead = value;}
}
private int _ladderFoot; // points to another node where to player goes up to
public int LadderFoot
{
get {return _ladderFoot;}
set {_ladderFoot = value;}
}
}
Answer to your question:
In C++ fields of struct are public by default
In C# fields of struct are private by default
You have declared fields without access modifier keyword (private.public`) so they have default accessibility mentioned above.
To get same behavior in C# you need declare access modifier explicitly
struct Node
{
public int snakeHead ;to
public int ladderFoot;
}
Notice that in C++ fields of classes are private by default.
The default access modifier is private. Create properties to access your private fields.
class Node
{
int snakeHead ; // points to another node where the player goes down to
int ladderFoot; // points to another node where to player goes up to
public int SnakeHead
{
get { return snakeHead;}
set { snakeHead = value;}
}
public int LadderFoot
{
get { return ladderFoot; }
set { ladderFoot = value;}
}
}
After that you can gameBoard[i].SnakeHead = 0;
You can even define the properties like this:
public int SnakeHead{get; set;}
In this case you will not even need the private fields.
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.
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 6 years ago.
Improve this question
Sometimes it happens that I want to use a lot of Method As variables in Method B.
Usually its quite a pain to pass all the variables to this method, especially if I have to do this a lot of times (but cannot simply copy paste, because some things change) or am just to lazy.
Is there such a thing like a "inner Method"? Or some concept to handle this in an easy way?
What I want to do:
public void A()
{
int a = 4;
string b = "Hello World";
B(ref vals);
//Or like so
C(ref current);
}
public void B(ref AllValues)
{
a = 3;
...
}
public void C(ref MethodThatSharesAllValues method)
{
method.a = 3;
...
}
If they all are in the same class
You can configure them as class variables:
public class MyClass{
//set this as private/protected/public or nothing and you can also set a default value
int a;
public void A()
{
a = 4;
string b = "Hello World";
B();
C();
}
public void B()
{
a = 3;
...
}
public void C()
{
a = 3;
...
}
}
Elseway
public static class MyClassA{
public static int a = 0;
public static void MethodA(){
this.a = 3;
}
}
now from method B you can access MyClassA
int myExValueA = MyClassA.a;
Elseway you gotta pass them as parameters
hope this helps
You can create a class which will hold your parameters and then pass only an instance of this class
public void metA(Parameters input)
{
input.a = 5;
input.c = "hello";
metB(input);
}
public void metB(Parameters input)
{
input.b = 10;
}
public class Parameters
{
public int a;
public int b;
public string c;
}
You can declare the variables static in a class header and use them as you like, private if are in the same class, protected for child classes, internal or public else. Or box the variables in a class like this:
public class Foo
{
public int A { get; set; }
public int B { get; set; }
public string C { get; set; }
}
If passed variables are the same type you can use data structure like int[] or string[] or List<int> or List<string> and pass them without ref but this has the disadvantage that more than often you would not use all varibales from the structure as it is also the case with the class boxing variant.
Something like the following:
public void foo() {
int a = 10;
// ...
}
public void foo_bar() {
// "a" is not in scope for foo_bar, so this won't compile
a = 20;
// ...
}
would definitely be invalid. I don't think that this was what you were driving at in your question though.
You can do something somewhat similar to what you ask for using closures but they're a bit tricky to work with. Basically, something like this would be valid (and I'm not sitting in front of an IDE so forgive me if the syntax is a little off):
Func<int> GetCounter() {
int count = 0;
// This will capture the count variable from its context
Func<int> method = () => ++count;
return method;
}
While a fair number of languages (including some versions of C++ now I guess) have closures (or some similar variant), there seems to be little consistency in exactly how they work across languages (e.g. on whether the "count" variable should be immutable once it's captured) so it's important to check the documentation for the language you're using (in this case, C#) to understand exactly how they work.
In terms of the first code sample I provide, I doubt that that's what you were asking about, but just as a brief digression you probably wouldn't really want it to be the allowable anyway (and again I suspect that this isn't the syntax/semantics you're asking about) as it would quickly lead to unexpected/undefined behavior. For example:
If you have a local variable a that's initialized in Foo() and you refer to it in Foo_Bar() before you run Foo(), what should its value be?
If you run Foo() to initialize the variable, edit the variable in Foo_Bar(), and then run Foo() again, should you re-initialize the variable or allow it to remain what Foo_Bar() set it to?
Is it safe to garbage collect a local variable after the method call completes, or might it be referred to again?
See the following:
public class SomeObject
{
public int SomeProperty { get; set; } = 6;
// ...
}
public class SomeOtherObject
{
// ..
}
void foo() {
// What is the content of "a" before foo() runs?
object a = new SomeObject();
// Which "a" should this refer to - the one in foo() or the one in foo_bar()?
// Also, is this a valid cast given that we haven't specified that SomeOtherObject can be cast to SomeObject?
var b = (SomeObject)a;
// If we run foo() again, should "b" retain the value of SetProperty or set it back to the initial value (6)?
b.SetProperty = 10;
// ...
// Is it safe to garbage collect "a" at this point (or will foo_bar refer to it)?
}
void foo_bar() {
object a = new SomeOtherObject();
// ...
}
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.