It's been a long while since I have done anything with C# and I decided I wanted to give it a go again. Basically I want to create a class add some variables to it that I can reference outside of the class.
class classname (variablename)
{
function
}
classname (varaiblename = value)
I understand this is probably very much incorrect but that is the gist of wha tI would like to do.
Thank you very much for your time.
You're looking for Properties:
class Foo
{
public int Bar { get; set;}
}
Foo obj = new Foo();
obj.Bar = 5;
I think you need public static variables:
Let's say you've integer variable in class A and you want to control this variable from other classes. There's static variable term which let's you change value of static variables from other classes and it'll affect all of the instance of classes:
Here is my quick code:
public class A {
public static int myValue = 5;
}
So, when you declare your variable like this, you can use and control this variable from other classes such as:
Console.WriteLine(A.myValue); or A.myValue += 5;
Related
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.
I have two .cs files (Hex2Bin.cs and Program.cs) and I want to pass the variable end_addr from Program.cs to Hex2Bin.cs
My code in Program.cs:
class Program
{
enum to_exit {
exit_ok = 0,
exit_invalid_args,
exit_to_few_args,
exit_invalid_input_file,
exit_invalid_args_file,
exit_permission_denied,
exit_unexpected_eof
};
// class value holders
static String args_file_name = "";
static String in_u1_name = "";
static String in_u22_name = "";
static String out_name = "";
static short end_addr = 0x0000; // 4-digit Hexadecimal end address
static Byte[] version_code = { 0, 0, 0, 0 }; // 3 bytes version, 1 for extra info
}
Is there anyway I could do this? I know how to do it in c, but I'm very new to c#. Thanks.
C# doesn't work like C with respect to static variables. You can make the variable end_addr available outside the Program class by making it a public field. By default, fields are private.
public static end_addr = 0x0000;
And then it can be accessed like so:
var x = Program.end_addr;
However, I would recommend that you spend a little more time familiarizing yourself with C# idioms and conventions. It seems like your still thinking about C# in terms of C, and they are very different.
if you declare the variable like this:
public static short end_addr = 0x0000;
then from another class you can use it like this:
Program.end_addr
but don't do this, is not object oriented!
if your class Hex2Bin is used/invoked by the Main method of Program class, you should be able to pass your variables as input parameters of the methods you call or set them as properties of the classes/objects you use...
It's enough to mark end_addr as public like so
public static short end_addr = 0x0000;
Then you can access it from anywhere like this
Program.end_addr
It's a better practice though to use properties rather than fields for exposing data.
// Property
public static short end_addr { get; private set; }
// Constructor
public Program()
{
// Initialize property value.
end_addr = 0x0000;
}
You're talking about 'files' but what you really want to do is to pass data from your program's entry point (Program.cs) to a an object of a class (or method of static class) that will process the data, am I right?
If so, this should be pretty simple. You either have to modify your Program.cs and create an instance of the class (the one from Hex2Bin.cs) like this
...
Hex2Bin hex2bin = new Hex2Bin( end_addr );
...
I assume that the Hex2Bin is as follows:
public class Hex2Bin
{
private short endAddress;
public Hex2Bin( short endAddress )
{
this.endAddress = endAddress;
}
}
this will allow you to use the value of end_addr from Program.cs
Another approach is to pass it directly to the method that will make use of it:
Hex2Bin.Method(end_addr);
and in the Hex2Bin file:
public static void Method(short endAddress)
{
//... do the work here
}
Given your background in C, I think you may be mixing runtime with compile time issues.
However, in Hex2Bin.cs, you can create a static method that updates a static variable.
class Hex2Bin
{
static short end_addr = 0x0000;
static void updateEndAddr(short endAddr)
{
end_addr = endAddr;
}
}
I have a class called RandomGen which generates random variables when called like so:
RandomGen u = new RandomGen();
int QRNOne = u.QuestionRandNo(n);
n++;
How do I then set QRNOne as a global variable to be accessed later? Also, can I do this from within the class, and have it create this variable? (I realise there is no "real" global variable in C# WPF, but you ought to understand what I'm referring to.)
Please read up on static class members.
I'm sure you know that global variables are best avoided if possible, but if you really need a static member variable then you would do something like this:
public class MyClass
{
public static int QRNOne {get; private set;}
public void GenerateRandom(){ ... ; QRNOne = ...; }
}
And then refer to that variable from elsewhere as
public void SomeOtherMethod()
{
int qr = MyClass.QRNone;
...
}
Can you use a static, Singleton style class with properties tor the values you want to use? This should then have global visibilty with sufficient structure and encapsulation.
We are transfering our code from C++ to C# and due to limited knowledge of C# we are stuck into strange situation. Our problem is:
In c++ we have 2-3 types of class/structures which have pointers to property (std::string), purpose of pointer is to make sure that all the instance for similar object will point to same property. e.g
struct st1{
string strVal;
};
struct st2{
string* strVal;
};
//At time of creation
st1* objst1 = new st1();
st2* objst2 = new st2();
objst2.strVal = &objst1.strVal;
//After this at all point both object will point to same value.
I want this kind of architecture C#, I got some suggestion like:
Declare events
Make code unsafe and use pointers (but I think this will lead to some other problems)
Please let me know if something better and near to C++ can be done here..
In C# all clases are references / pointers. So as long as your property is of class type, you can have same instance in different structures.
But problem can arise when you use string. While it is class and reference property, it is enforced to be imutable. So when you change it, you dont change the instance itself, but you create new copy with those changes.
One solution that comes to mind is to create custom string class, that will simply contain string and use it as your type:
public class ReferenceString
{
public String Value { get; set; }
}
You could use a static property with inheritance:
class thing
{
static string stringThing;
public string StringThing
{
get { return stringThing; }
set { stringThing = value; }
}
}
class thing2 : thing
{
}
Then later:
thing theThing = new thing();
theThing.StringThing = "hello";
thing2 theThing2 = new thing2();
// theThing2.StringThing is "hello"
well... I'm confused about what can I do and what I can't do in CLASS SCOPE.
For example
=========================
class myclass
{
int myint = 0;
myint = 5; *// this doesnt work. Intellisense doesn't letme work with myint... why?*
void method()
{
myint = 5; *//this works. but why inside a method?*
}
}
==================================
class class1
{
public int myint;
}
class class2
{
class1 Z = new class1();
Z.myint = 5; *//this doesnt work. like Z doesnt exists for intellisense*
void method()
{
Z.myint = 5; *//this Works, but why inside a method?*
}
}
Thats I make so many mistakes, I dont understand what works on class scope and what doesnt work.
I know that there are local varaibles and its life cycle. But I dont understand the so well the idea.
A class can only contain declarations, initializations, and methods. It cannot contain statements of its own.
class MyClass
{
int x; // a declaration: okay
int y = 5; // a declaration with an initialization: okay
int GetZ() { return x + y; } // a method: okay
x = y; // a statement: not okay
}
You can initialize a field, but you can't just have assignment statements.
You can't do the below:
class myclass
{
int myint = 0;
myint = 5;
Because there is nothing to do, you can only declare members and possibly set an initial value. It is nothing to do with scope. One of the reeasons you can't do it is that there is no guarantee of order, the compiler just gurantees all values will be initialised by the time the class is instantiated. That is why you also cannot do the following:
class myclass
{
int myint = 0;
int MyOtherInt = myint;
If you want to set the value when the class is instantiated, put it in the contructor.
Basically, when you create a class, you are not allowed to have code & assignments inside that class directly.
but as c# wants to help you, it allows you to define initial states for fields. and they are basically executed directly bevore your constructor code.
when you now want to define code inside the class. somewhere... the program would not know, when to execute. so they are forbidden.
A class definition defines its makeup, that is, the fields, properties, methods, events, etc. that it contains. The "work" is actually done inside methods.
What you seem to be confusing is the initialization of the fields of a class with the usage of those fields. You can initialize a field outside a method definition, but to use it, you need to be inside a method.
To clearly understand it and get answers on your questions you should read Jeffrey's Richter "CLR via C#, Third Edition" and C# 4.0 Language Spectification