I want to get value from other cs file - c#

I want to get value from other cs file.
for example. there are two cs files in same Project.
one is A.cs, another is B.cs
And there is a variable in A.cs
int a = 1;
i want to use variable 'a' in B.cs, like this
int b = a;
then what should i do?

try making your variables static then you can access it any other file
Here is Explanation:
First file: A.cs
class A
{
public static int a=4;
}
Secound file: B.cs
class B
{
public int b=A.a;
}

If they are in the same namespace you will need to change the default access modifier to allow access. I believe the default is protected. More info here https://msdn.microsoft.com/en-us/library/wxh6fsc7.aspx
You would need to change int a = 1 to something like
internal class ClassA
{
internal int a = 2;
}
then you would instiate a from b
ClassA classA = new ClassA();
b = classA.a;

public class A
{
public int intA = 1;
}
now, call it in B.cs
public class B
{
A = new A();
var valueA = A.intA;
}

Related

How to call a variable from a class without calling the class - c#?

I want to use a const variable from this class:
class foo
{
public const bool x = true;
}
is there any way to use x without doing foo.x?
i want to use it like this:
if( x )
and not like this:
if( foo.x )
The only way to achieve that is to mark foo as static and use using static where you want to have access to foo.x as x.
namespace Foo
{
static class Bar
{
public const bool x = true;
}
}
and later:
using static Foo.Bar;
Console.WriteLine(x);
using static is a C# feature, so make sure you're using C# 6 before you use it.
No, a member always stays a member of a class, so you either have to call a static (or constant) variable through the class name, or call the member on the instance.
So this would work:
public class Foo { public static int SomeInt {get;set;} = 12; }
int i = Foo.SomeInt;
Or:
public class Foo { public int SomeInt {get;set;} = 12; }
Foo f = new Foo();
int i = foo.SomeInt;
And as shown by Marcin, you can somewhat hide that truth by using using static. Still, it is called through the class.
For starters it will need to be publicly accessible
public class foo
{
public const bool x = true;
}
And then you can store the value in a variable
var x = foo.x;
if(x) { .. }

C# anonymous value types nature

Consider the flowing code snippet
static void Main()
{
var x = new MyStruct
{
Item = new StringWrapper("abc")
};
Console.WriteLine(x.Item.PublicField);
x.Item.SetValue("xyz");
Console.WriteLine(x.Item.PublicField);
var y = new
{
Item = new StringWrapper("abc")
};
Console.WriteLine(y.Item.PublicField);
y.Item.SetValue("xyz");
Console.WriteLine(y.Item.PublicField);
}
public struct MyStruct
{
public StringWrapper Item;
}
public struct StringWrapper
{
public string PublicField;
public StringWrapper(string v)
{
PublicField = v;
}
public void SetValue(string v)
{
PublicField = v;
}
}
And the output:
abc
xyz
abc
abc
MyStruct can be declared as class, and the output will remain the same.
{abc, abc} part of output is a surprise for me, as I expect anonymous type to be converted to class or struct and behave the same.
I feel like I'm missing something obvious here and will appreciate any help.
Thanks.
The difference here is that your MyStruct (struct or class) exposes a public field while anonymous classes (new { }) expose public properties.
When you access a value type from a field or variable, you do not get a copy, you access the instance directly. Therefore making changes to it stores them in the instance.
When you instead access it via a property or method, you get a returned copy of your StringWrapper and changing that doesn't change what is stored in the anonymous classes private field.
Just to demonstrate, you can get the same behavior by making your Item field a property too:
public StringWrapper Item { get; set; }

Creating a copy of an object in C# [duplicate]

This question already has answers here:
How do you do a deep copy of an object in .NET? [duplicate]
(10 answers)
Closed 3 years ago.
Please have a look at the code below (excerpt from a C# book):
public class MyClass
{
public int val;
}
public struct myStruct
{
public int val;
}
public class Program
{
private static void Main(string[] args)
{
MyClass objectA = new MyClass();
MyClass objectB = objectA;
objectA.val = 10;
objectB.val = 20;
myStruct structA = new myStruct();
myStruct structB = structA;
structA.val = 30;
structB.val = 40;
Console.WriteLine("objectA.val = {0}", objectA.val);
Console.WriteLine("objectB.val = {0}", objectB.val);
Console.WriteLine("structA.val = {0}", structA.val);
Console.WriteLine("structB.val = {0}", structB.val);
Console.ReadKey();
}
}
I understands it produces the output below:
objectA.val = 20
objectB.val = 20
structA.val = 30
structB.val = 40
The last two lines of the output I have no problem with, but the first two tell me that objectA and objectB are pointing to the same memory block (since in C#, objects are reference types).
The question is how do make objectB, a copy of objectA so that it points to a different area in memory. I understand that trying to assign their members may not work since those members may be references, too. So how do I go about making objectB a completely different entity from objectA?
You could do:
class myClass : ICloneable
{
public String test;
public object Clone()
{
return this.MemberwiseClone();
}
}
then you can do
myClass a = new myClass();
myClass b = (myClass)a.Clone();
N.B. MemberwiseClone() Creates a shallow copy of the current System.Object.
There is no built-in way. You can have MyClass implement the IClonable interface (but it is sort of deprecated) or just write your own Copy/Clone method. In either case you will have to write some code.
For big objects you could consider Serialization + Deserialization (through a MemoryStream), just to reuse existing code.
Whatever the method, think carefully about what "a copy" means exactly. How deep should it go, are there Id fields to be excepted etc.
The easiest way to do this is writing a copy constructor in the MyClass class.
Something like this:
namespace Example
{
class MyClass
{
public int val;
public MyClass()
{
}
public MyClass(MyClass other)
{
val = other.val;
}
}
}
The second constructor simply accepts a parameter of his own type (the one you want to copy) and creates a new object assigned with the same value
class Program
{
static void Main(string[] args)
{
MyClass objectA = new MyClass();
MyClass objectB = new MyClass(objectA);
objectA.val = 10;
objectB.val = 20;
Console.WriteLine("objectA.val = {0}", objectA.val);
Console.WriteLine("objectB.val = {0}", objectB.val);
Console.ReadKey();
}
}
output:
objectA.val = 10
objectB.val = 20
There's already a question about this, you could perhaps read it
Deep cloning objects
There's no Clone() method as it exists in Java for example, but you could include a copy constructor in your clases, that's another good approach.
class A
{
private int attr
public int Attr
{
get { return attr; }
set { attr = value }
}
public A()
{
}
public A(A p)
{
this.attr = p.Attr;
}
}
This would be an example, copying the member 'Attr' when building the new object.

C# compiler error: "cannot have instance field initializers in structs"

I need advice on structures.
I have 2 sections of code. The first section is as below:
namespace Project.GlobalVariables
{
class IOCard
{
struct InputCard
{
public string CardNo;
public int BaseAddress;
public int LowerAddress;
public int UpperAddress;
public int[] WriteBitNo = new int[16];
public int[] ReadBitNo = new int[16];
}
static InputCard[] InputCards = new InputCard[5];
public static string ACardNo = InputCards[1].CardNo;
public static string BCardNo = InputCards[2].CardNo;
}
}
The second portion is as below:
private void Form1_Load(object sender, EventArgs e)
{
IOCard.ACardNo = "Card A";
IOCard.BCardNo = "Card B";
MessageBox.Show(IOCard.ACardNo);
MessageBox.Show(IOCard.BCardNo);
}
My plan is to be able to assign and retrieve InputCards component by using IOCard as shown in Form1_Load.
However, when I compile the code, I get the following error.
Error 1 'Project.GlobalVariables.IOCard.InputCard.WriteBitNo': cannot have instance field initializers in structs E:\Programming\New platform\StandardPlatform\StandardPlatform\Project\GlobalVariables.cs 16 26 StandardPlatform
Can someone tell me how to solve the error?
Please advise. Thanks.
Here are the classes that I have attempted to create and use, but failed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Project.GlobalVariables
{
static class IOCard
{
public const int TotalInputCard = 10;
public const int TotalOutputCard = 10;
public class InputCard
{
public string CardNo = "1";
public int BaseAddress;
public int LowerAddress;
public int UpperAddress;
public int[] WriteBitNo = new int[16];
public int[] ReadBitNo = new int[16];
}
public class OutputCard
{
public string CardNo;
public int BaseAddress;
public int LowerAddress;
public int UpperAddress;
public int[] WriteBitNo = new int[16];
public int[] ReadBitNo = new int[16];
}
public static InputCard[] InputCards = new InputCard[TotalInputCard];
public static OutputCard[] OutputCards = new OutputCard[TotalOutputCard];
public static int X100 = InputCards[0].WriteBitNo[0];
public static int Y100 = OutputCards[0].WriteBitNo[0];
}
}
I tried to use these in the Form_Load, like so:
private void Form1_Load(object sender, EventArgs e)
{
IOCard.X100 = 1;
IOCard.Y100 = 1;
}
No matter how much I have tried to search on the net for answers, I have got nowhere.
Please advise. Thanks.
In C#, a struct value is not a reference to an object in the way a value of a class type is. The value of a struct is the "union" of all the values of the instance fields of the struct.
Now, the default value of a struct type is the value where all those fields have their default values. Since the beginning of C#, the syntax:
new S() // S is a value-type
where S is a struct type, has been equivalent to the default value of that struct. There is no constructor call! This is the exact same value which can (nowadays) also be written
default(S) // S is a value-type
Now, things like
struct S
{
int field = 42; // non-static field with initializer, disallowed!
// ...
}
are illegal (cannot have instance field initializers in structs). They could give the impression that the field of a new S() would be 42, but in fact the field of new S() must be the default value of int (which is zero, distinct from 42).
With this explanation, you also see why it is not possible to create a non-static, zero-parameter constructor for a struct type, in C#.
What's it's trying to say is that when you have InputCards = new InputCard[5]; it will allocate a block of memory 5 times the size of an InputCard structure and set all of its bytes to 0. There is no opportunity to execute the int[] WriteBitNo = new int[16]; and such assignments, so you cannot have them.
Your options are to either manually call an initializer for your structs or make it a class and manually initialize the InputCards array with 5 new instances of InputCard.
You will neither be able to initialize a struct's fields nor define a default constructor to initialize it's fields. After looking at your struct, I recommend you use a class instead. It's not recommended to use a struct for a scenario where you have a bunch of fields.
Try this. Initialize the InputCard with a factory function Create():
namespace Project.GlobalVariables
{
class IOCard
{
struct InputCard
{
public string CardNo;
public int BaseAddress;
public int LowerAddress;
public int UpperAddress;
public int[] WriteBitNo;
public int[] ReadBitNo;
static InputCard Create()
{
return new InputCard()
{
CardNo = string.Empty,
WriteBitNo = new int[16],
ReadBitNo = new int[16]
};
}
}
static InputCard[] InputCards = new InputCard[]
{
InputCard.Create(),
InputCard.Create(),
InputCard.Create(),
InputCard.Create(),
InputCard.Create()
};
public static string ACardNo = InputCards[1].CardNo;
public static string BCardNo = InputCards[2].CardNo;
}
}
Use class instead of structure. Structure is used for small types like Point, which are faster to create on the stack and copy, than to create dynamically and pass by reference.
Not sure about the exception, but i have a solution.
You should not use "struct" for this class, it is too much (and storing too much data). If you define it as "class", the same code would work fine.
Is there a particular reason why you want this to be a struct rather than a class?
If you make it a class, it works just fine.

Object Behaviour

Can anyone explain the behaviour of the below code. The output of the below code is string "str" and i's value is 100.
But why is it so? After setting object c1 = null, why isn't it null?
public class Class1
{
public int i;
public Class1()
{
i = 10;
}
public string method1()
{
return "str";
}
}
public class Class2
{
public void method2(Class1 c1)
{
c1.i = 100;
c1 = null;
}
}
void main()
{
Class1 c1 = new Class1();
Class2 c2 = new Class2();
c2.method2(c1);
Response.Write(c1.method1());
Response.Write(c1.i.ToString());
}
When you call method2(Class1 c1) you are passing a copy of the reference to the object, not the object itself (or the reference to it). When you set c1 = null you are setting the copy of the reference to be null, not the object.
You can get the behaviour you expect by changing your method signature to this:
method2(ref Class1 c1)
In C#, references are passed by value. That is, method2 receives a copy of the value of the reference to c1.
In method2 setting c1 = null affects the local copy of the reference only.
See this article for more info
This is a pass-by-reference/pass-by-value thing. Javaranch Camp site stories: Pass By Value Please explains it very well. I know the above link is for Java, and this is a C# question, but the same thing happens (unless the "ref" keyword is used).
Hopefully a simple edit of your code can show you why:
public class Class1
{
public int i;
public Class1()
{
i = 10;
}
public string method1()
{
return "str";
}
}
public class Class2
{
public void method2(Class1 myLocalReference)
{
myLocalReference.i = 100;
myLocalReference = null;
}
}
void main()
{
Class1 c1 = new Class1();
Class2 c2 = new Class2();
c2.method2(c1);
Response.Write(c1.method1());
Response.Write(c1.i.ToString());
}
I think that shows clearly that the reference used in Class2.method2 isn't the same as that used in main. c1 is declared in main, when used as a parameter in the method call c2.method2(c1); the reference to your Class1 instances is copied into a new local value called myLocalReference. You then set myLocalReference = null; and within method2 you would find that Response.Write(myLocalReference.method1()); or Response.Write(myLocalReference.i.ToString()); would fail appropriately. When method2 exits the local reference myLocalReference goes out of scope and you return to main where the c1 reference exists and is unchanged so the subsequent Response.Write methods succeed.

Categories