-
[C#] question
hi all
i need som help
i am filling a string in a class but when i open that string in a difrent class it's empty.
can some on explain why
Code:
using System;
namespace NameTest
{
class teststring2
{
public string test;
}
class teststring
{
static void Main()
{
teststring3.test();
teststring2 TestStr = new teststring2();
Console.WriteLine("lets look at the string again " + "\" " + TestStr.test + " \""+" it should be here but its not why");
Console.ReadLine();
}
}
class teststring3
{
public static void test()
{
teststring2 TestStr = new teststring2();
TestStr.test = "\"Hi\"";
Console.WriteLine("lets look at the string " + TestStr.test);
Console.ReadLine();
}
}
}
do you know how to fix this ore make it a difrent way
-
Re: [C#] question
Well first of all, your program makes no sense. :tongue:
As for the reason it doesn't work, when you declare TestStr within the member function test() of teststring3, it exists only locally inside that function and will cease to exist as soon as execution of the function ends.
The other TestStr you declare in main() is a whole another variable.
I don't have the slightest idea what you're trying to test with this, but it doesn't quite look like you have a good idea of what classes are intended for. Btw, try to use indentation, because it will improve readability by 100%.
-
Re: [C#] question
That code is absolutely horrible...
But what you're doing is Declaring two instances of the class teststring2
You declare one when you're writing it to the console, and also one where you set 'test' to Hi.
And so when you write it for the second time - Your new class's instance of 'test' is going to be null
This is what i 'think' you're trying to do
Code:
class TestString
{
public string Test;
}
class Program
{
static void Main()
{
TestClass.tst = new TestString();
TestClass.setTestString("Hello World!");
Console.WriteLine(TestClass.GetTestString());
Console.ReadLine();
}
}
class TestClass
{
private static TestString tst;
public static string getTestString()
{
return tst.Test;
}
public static void setTestString(string Value)
{
tst.Test = Value;
}
}
But again its a really bad way to do it and seems pointless having 2 classes when you could just have the one class or even no classes (Since you're just using a string..)
-
Re: [C#] question
thanks fore all your help
fixt it