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.
Related
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.
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 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.
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 9 years ago.
Improve this question
Without constructor how you initialize a class variables ?
For Example , I have a class with two variables name as "x" and "y" data type as string. By creating an object for the class I need to initialize some value to these variables , without involvement of Constructor . Can u please any one help me ?
You can use the Object Initializer feature:
var obj = new yourclass { x = "abc", y = "xyz" };
Although, this will work only if the variable x and y are public. Or, in other words, if they are accessible to the code where you are instantiating the class.
You can put an initializer when you create the variables:
private string foo = "val1";
You can initialize the default values to private variables directly by initializing them as
public class A
{
private int X= 5; //Like this
private int Y= 6
}
You can do it just like with a local variable like this:
class MyClass
{
string x = "x";
string y = "y";
}
when you create an object for your class using new keyword default constructor will be invoked and all your class data members will be initialised to their default type values.
Ex:
Class Student
{
String strName;
String strAddress;
}
Student student1=new Student();//this will call default constructor
the above statement calls the Default Construdtor and it will initialise the values to their default types as below.
public Student
{
strName=String.Empty;
strAddress=String.Empty;
}
if you want to initialise your class variables with some specific values then you can create parameterised constructor or initialise them normally.
String x="some value";
String y="some value";
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.