public void main()
{
string test = "testing";
ChangeVal(test);
Console.WriteLine(test);
}
private void ChangeVal(string test)
{
test = "in child";
}
If String is a class.
and i pass string as a parameter to a function. change the value of that string in function.
But in main function it shows the previous values. It will print testing value.
when i created Foo class which has 2 member variable integer and string.
when i passed the object of the class as parameter and change value of the member variable in function.
It will give updated value in the main function
public class Foo
{
public string test = "testing";
public int i = 5;
}
public void main()
{
Foo obj=new Foo();
Console.WriteLine(obj.test);
ChangeVal(obj);
Console.WriteLine(obj.test);
}
private void ChangeVal(Foo obj)
{
obj.test = "in child";
obj.i = 5;
}
If string is the class. It will update the value of the variable.
May string is the sequence of Unicode character that's why it doesn't update the value in 1st case.
Can any body will explain this in detail.
change the value of that string in function
Strings are immutable. You can't change the value of a string. You can assign another string to the same reference, but you would need to pass the reference in by using ref.
public void main()
{
string test = "testing";
ChangeVal(ref test);
Console.WriteLine(test);
}
private void ChangeVal(ref string test)
{
test = "in child";
}
You Foo class, however, is mutable, so you can assign different values to its members.
Try to pass the parameter by reference to get the var updated in main thread:
private void SeString(ref string chain)
{
chain="new string";
}
Then call:
string variable="hello";
SeString(ref variable);
string output is "new string"
Related
Simply put how do you establish a connection between method variable decloration and connect it with class properties (or inner objects), lets say you have default or hard set values in a class like this (obviously they could be other types but for simplicity its set to strings) :
public class SampleClass
{
public string strA = "Something 1";
public string strB = "Something 2";
public string strC = "Something 3";
}
//think of it as a data layer where strings are pointers to dbSets
How do you leverage the same SampleClass in a method that allows ONLY pick of properties Method(property).
Easy sample that does what its supposed to:
public class ProccessClass
{
private string _dummyOut;
public ProccessClass Pick(string input)
{
this._dummyOut = input;
return this;
}
}
class Program
{
static void Main(string[] args)
{
var Test = new ProccessClass().Pick(new SampleClass().strB);
// we know this works and compiles and returns the strB
}
}
What would you have to convert to ommit the new instantiation and skip the class declaration (if possible but in theory should be doable)
new SampleClass().strB
needs to be just
strB
So how to get the final code to execute??
public class SampleClass
{
public string strA = "Something 1";
public string strB = "Something 2";
public string strC = "Something 3";
}
public class ProccessClass
{
private string _dummyOut;
public ProccessClass Pick(SampleClass sampleClass) //is it the variable declaration?
{
this._dummyOut = input;
return this;
}
}
class Program
{
static void Main(string[] args)
{
string Test = new ProccessClass().Pick(strB);
//so NO new keywords clean and easy set based on class provided above
}
}
Constructor and void setters but no go, the goal is to set the Hard relation ship between the method intake value and setters
I need to get string from one class to another class,
It is possible to set public string from method I mean like in this code:
class test
{
static void Main(string[] args)
{
load();
}
public class Data
{
public string datacollected { get; set; }
}
public static void load()
{
string fileName = "samplefile.json";
string jsonString = File.ReadAllText(fileName);
Data datacfg = new Data();
var datanew = System.Text.Json.JsonSerializer.Deserialize<List<Data>>(jsonString);
datacfg = datanew.First();
}
public string datacollected = datacfg.datacollected;
}
i want to use string datacollected in another class and in another public void
The datacollected member that is directly in the test class is not a property. It's a field. Fields that have an assignment on the same statement as the declaration are evaluated before* the class's constructor (ie: before the Main method runs).
You probably want it to be a property instead, which is evaluated each time you access the member. The simplest method to fix that is by adding a > after the equals.
public string datacollected => datacfg.datacollected;
You've got two other problems though.
datacollected (in the test class) isn't static. All of your methods are static, and therefor wouldn't be able to access the non-static member.
You've still got the problem where the datacfg is a local variable that is defined inside the load method. You can't use variables outside their defined scope.
Option 1: you only need the parsed file data in the method that called load.
Change load to return the parsed data, rather than save it to a class-global variable.
using System.Text.Json;
static class test
{
static void Main(string[] args)
{
Data loadedData = load();
}
public static Data load()
{
string fileName = "samplefile.json";
string jsonString = File.ReadAllText(fileName);
return JsonSerializer.Deserialize<List<Data>>(jsonString).First();
}
}
public class Data
{
public string datacollected { get; set; }
}
Option 2: If you really need some global variable, put the whole Data object up to a field instead. This doesn't use a property - there's really no advantage in this case.
using System.Text.Json;
static class test
{
// assuming you're using nullable reference types (the "?")
private static Data? loadedData;
static void Main(string[] args)
{
load();
Console.WriteLine(loadedData!.datacollected);
// "!" to tell compiler that you know loadedData
// shouldn't be null when executed
}
public static void load()
{
string fileName = "samplefile.json";
string jsonString = File.ReadAllText(fileName);
loadedData = JsonSerializer.Deserialize<List<Data>>(jsonString).First();
}
}
public class Data
{
public string datacollected { get; set; }
}
I'd go with Option 1 if at all possible.
* I don't remember if it's before, during, or after.
You can declare a class like this
public class UseData
{
private List<Data> _data=null;
public string datacollected
{
get
{
if (_data == null)
LoadData();
return _data.First().datacollected;
}
}
private void LoadData()
{
string fileName = "samplefile.json";
string jsonString = File.ReadAllText(fileName);
_data = System.Text.Json.JsonSerializer.Deserialize<List<Data>>(jsonString);
}
}
which have a private list of data and it loads from your json file at first time you called. Next time you call it, as the private _data object is filled, it wont load again and the datacollected property returns the first data object's datacollected string property.
As this.name is not working to access fields with the same name like a method parameter in static classes, I'm looking for a way to do so.
As an example i would like to do this:
static class test
{
private static string aString;
public static void method(string aString)
{
// aString (field) = aString (parameter)
}
}
use:
test.Astring = x;
i.e. replace this with the class name, test in this case.
static class test
{
private static string Astring="static";
public static void method(string Astring)
{
string passedString = Astring; // will be the passed value
string staticField = test.Astring; // will be static
}
}
if we call the method like test.method("Parameter"); the staticField will have the value static and passedString will have the value Parameter.
The keyword this denotes the current instance of the class; static
fields cannot be accessed through instance you should use the class
name instead for accessing the static field.
Note :- But please take care while naming the variables. Avoid giving same name in same class. It will be best if you define the class like the following
static class test
{
private static string StaticAstring="static";
public static void method(string passedAstring)
{
string staticField = StaticAstring; // will be static
string passedString = passedAstring; // will be the passed value
}
}
I've trying to achieve something like this:
class App {
static void Main(string[] args) {
System.Console.WriteLine(new Test("abc")); //output: 'abc'
System.Console.ReadLine();
}
}
I can do this passing by an variable:
class Test {
public static string str;
public Test (string input) { str = input; }
public override string ToString() {
return str;
}
}
works fine.
But, my desire is do something as:
class Test {
public static string input;
public Test (out input) { }
public override string ToString() {
return input;
}
}
System.Console.WriteLine(new Test("abc test")); //abc test
Don't works.
How I do this?
Thanks,advanced.
You can't. The variable approach is exactly the correct way, although the variable shouldn't be declared static, and shouldn't be a public field.
class Test {
public string Input {get;set;}
public Test (string input) { Input = input; }
public override string ToString() {
return Input;
}
}
I have an impression that you're not entirely understand what out keyword means. Essentially when you're writing something like void MyMethod(out string var) it means you want to return some value from method, not pass it into method.
For example there's bool Int32.TryParse(string s, out int result). It parses string s, returns if parse was successful and places parsed number to result. Thus, to correctly use out you should have real variable at the calling place. So you can't write Int32.Parse("10", 0) because this method can't assign result of 10 to 0. It needs real variable, like that:
int result;
bool success = Int32.TryParse("10", out result);
So, your desire is somewhat else - it is not in line with language designer's intentions for out :)
I am a C++ programmer, now working on a C# project.
I am trying to understand in the below snippet why the value of string does not change even though the function is changing its value, I thought it is an object and would be passed as a reference.
public class TestClass
{
public TestClass(String passedStr)
{
passedStr = "Change me";
}
}
class Program
{
static void Main(string[] args)
{
String aString="I am what i am";
TestClass obj = new TestClass(aString);
Console.WriteLine(aString);
}
}
But behavior with user defined classes are different.
public class TestClass
{
private int x;
public int ID
{
get
{
return x;
}
set
{
x = value;
}
}
public TestClass(int a)
{
x = a;
}
}
public class Tester
{
public Tester(TestClass obj)
{
obj.ID = 999;
}
}
class Program
{
static void Main(string[] args)
{
TestClass obj = new TestClass(555);
Tester tester = new Tester(obj);
Console.WriteLine(obj.ID);
}
}
Let's go back to basics.
A variable is a storage location.
A variable of type string is a storage location that stores either null, or a reference to a string.
"passedStr" and "aString" are different variables.
When you call "new TestClass(aString)" you create a new storage location for "passedStr" and copy the contents of "aString" into it. You now have two variables that have the same content: a reference to a string.
Inside the constructor you change the value stored in the storage location for "passedStr". "aString" remains the same.
The "ref" and "out" keywords in C# mean "make the formal parameter and the argument aliases of each other". In that case you have only one variable with two different names. When you change one of them the other one changes as well, because they are the same variable.
No, it's passed by value; there's no ref keyword.
It's passing a reference type (here, a class) by value (no ref keyword), just like passing a copy of a pointer in C++. You're reassigning the pointer, not the actual data (which you can't do with strings anyway).
If you need pass-by-reference, try:
public TestClass(ref String passedStr)
{
passedStr = "Change me";
}
...
TestClass obj = new TestClass(ref aString);
Strings are passed by reference but the pointer is passed by value in C#. If you want to pass the string by reference you'll have to make use of the ref key word.
For example:
public class TestClass
{
public TestClass(ref string passedStr)
{
passedStr = "Change me";
}
}
class Program
{
static void Main(string[] args)
{
string aString="I am what i am";
TestClass obj = new TestClass(ref aString);
Console.WriteLine(aString); // "Change me"
}
}
passedStr is not the string, but a constructor parameter that holds a reference to the string. All your TestClass constructor is doing is changing the string that this parameter references. It has no effect outside the constructor.
What you are doing in the constructor, is that you are assigning a new String literal to the local variable passedStr.
In C, the equivalent function would look something like this:
Testclass constructor_testclass(char* passedStr) {
passedStr = "Change me";
}
I think it's obvious that this function does not change the value of the char* in the calling function.
The object I am what i am is being passed by reference, but the reassignment is to a local variable. You don't change the original object, but instead assign a new object (Change me) to the location of the argument.
public class Employee
{
public string ID { get; set; }
public string Name { get; set; }
public override string ToString()
{
return string.Format("ID = {0} Name = {1}", ID, Name);
}
}
public class TestClass2
{
public TestClass2(Employee e)
{
e.ID="007";
e.Name="james";
}
}
static void Main()
{
Employee e = new Employee();
e.ID = "0";
e.Name = "nobody";
TestClass2 t = new TestClass2(e);
Console.WriteLine(e); //Output ID = 007 Name = James
}
strings are passed by reference but the pointer is passed by value in C#
Parameter passing in C# by Jon Skeet