Why this program output is "1". But it should have given "Null Reference exception" because I set it to null in xyz() method.
static void Main(string[] args)
{
A a = new A();
B b = new B();
b.xyz(a);
Console.WriteLine(a.x);
Console.ReadKey();
}
class A
{
public int x = 1;
}
class B
{
public void xyz(A a)
{
a = null;
}
}
You have set a copy of the variable a to null. This copy is created implicitly when the method xyz is called; that's because by default arguments in method calls are passed by value.
To get the exception you would need to pass the method's argument by reference:
public void xyz(ref A a)
{
a = null;
}
and then
b.xyz(ref a);
There is documentation on the subject on this MSDN page.
Related
I came across the following excerpt while reading on visibility guarantees provided by the JVM when reading volatile variables :
"When thread A writes to a volatile variable and subsequently thread B reads that same variable, the values of ALL variables that were visible to A prior to writing to the volatile variable become visible to B AFTER reading the volatile variable."
I have a question around this guarantee of JVM. Consider the below set of classes :
public class Test {
public static void main(String[] args) throws InterruptedException {
POJO p = new POJO();
new Th1(p).start();
new Th2(p).start();
}
}
public class Th1 extends Thread {
private POJO p1 = null;
public Th1(POJO obj) {
p1 = obj;
}
#Override
public void run() {
p1.a = 10; // t = 1
p1.b = 10; // t = 2
p1.c = 10; // t = 5;
System.out.println("p1.b val: " + p1.b); // t = 8
System.out.println("Thread Th1 finished"); // t = 9
}
}
public class Th2 extends Thread {
private POJO p2 = null;
public Th2(POJO obj) {
p2 = obj;
}
#Override
public void run() {
p2.a = 30; // t = 3
p2.b = 30; // t = 4
int x = p2.c; // t = 6
System.out.println("p2.b value: " + p2.b); // t = 7
}
}
public class POJO {
int a = 1;
int b = 1;
volatile int c = 1;
}
Imagine the 2 threads Th1 and Th2 run in separate CPUs and the order in which their instructions execute is indicated by the comment in each line (in their run methods). The question I have is that :
When code "int x = p2.c;" executes at t = 6, variables visible to thread Th2 should be refreshed from main memory as per the above para. The main memory then as I understand would have all the writes from Th1 at this point. What value will the variable p2.b show then when it is printed at t = 7?
Will p2.b show value of 10 as its value was refreshed from the read of the volatile variable p2.c?
Or it will retain the value 30 somehow?
For your code, p2.b is not guaranteed to be 10 or 30. The write is a race condition.
"When thread A writes to a volatile variable and subsequently thread B reads that same variable, the values of ALL variables that were visible to A prior to writing to the volatile variable become visible to B AFTER reading the volatile variable."
Your Th2 read of p2.c is not guaranteed to be done after the write of p1.c in Th1.
For the specific order you discussed, the read of p2.c in Th2 will not revert the value of p2.b to 10.
There is no happens before edge between the write of a and the read of a. Since they are conflicting actions (at least one of them is a write) and are on the same address, there is a data-race and as a consequence, program behavior is undefined.
I think the following example explains the behavior of what you are looking for better:
public class Test {
public static void main(String[] args) throws InterruptedException {
POJO p = new POJO();
new Th1(p).start();
new Th2(p).start();
}
}
public class Th1 extends Thread {
private POJO p1 = null;
public Th1(POJO obj) {
p1 = obj;
}
#Override
public void run() {
a=1;
b=1;
}
}
public class Th2 extends Thread {
private POJO p2 = null;
public Th2(POJO obj) {
p2 = obj;
}
#Override
public void run() {
if(p.b==1)println("a must be 1, a="+p2.a);
}
}
public class POJO {
int a = 0;
volatile int b = 0;
}
There is a happens before edge between the write of a and the write of b (program order rule)
There is a happens before edge between the write of b and a subsequent read of b (volatile variable rule)
There is a happens before edge between the read of b and the read of a (program order rule)
Since the happens before relation is transitive, there is a happens before edge between the write of a and the read of a. So the second thread should see the a=1 from the first thread.
Hello this question is regarding when exactly New keyword i;e Method hiding in base class can be done.
static void Main(string[] args)
{
A a = new A();
a.calculatebnft();
a = new B();
a.calculatebnft();
a = new C();
a.calculatebnft();
a = new Program();
a.calculatebnft();
Console.ReadKey();
}
public new string calculatebnft()
{
string bnft = "";
Console.WriteLine("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS");
return bnft;
}
}
class A
{
//my code here
public virtual string calculatebnft()
{
string bnft = "";
Console.WriteLine("A");//my code here
return bnft;
}
}
class B : A
{
//my code here
public override string calculatebnft()
{
string bnft = "";
Console.WriteLine("B");//my code here
return bnft;
}
}
class C : B
{
public new string calculatebnft()
{
string bnft = "";
Console.WriteLine("C");
return bnft;
}
}
When above program is executed output is
A
B
B
B
in this case New Keyword in class C not hiding method in class B? what is the reason behind it.
Sorry am new to .Net and if my question is too basic
I have created the class name cls1 and created method called GrantAccess().but the i am not able to access _entities.it's showing the below error
"Error 1 An object reference is required for the non-static field, method, or property 'Path._entities".
public class cls1
{
private readonly DBEntities _entities;
public cls1 ()
{
if (_entities == null)
{
_entities = new DBEntities();
}
}
public static void GrantAccess()
{
if (Settings.DbLog == "1")
{
_entities.II_CCLog("Excuting the GrantAccess() Method");
}
}
}
The above method is called in some other class.
public void GetCConfig()
{
cls1.GrantAccess();
}
GrantAccess is a static method while _entities is not a static variable. So you need to make GrantAccess a non-static method or you have to make _entities a static variable.
Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
Or create a new instance of DBEntities in the static GrantAccess method and perform your operation on this instance.
public static void GrantAccess()
{
if (Settings.DbLog == "1")
{
DBEntities entities = new DBEntities();
entities.II_CCLog("Excuting the GrantAccess() Method");
}
}
first you have to create an object of cls1 in the class where you are calling the method of the cls1 class and then with from that object reference you will be able to call the method GrantAccess();. You can create object by following way :-
variable_name = new class_name( );
You are mixing static code with instance code. If you're working with objects, don't make your method GrantAccess static:
public void GrantAccess()
{
if (Settings.DbLog == "1")
{
_entities.II_CCLog("Excuting the GrantAccess() Method");
}
}
Then you'll have to create an instance of cls1:
public void GetCConfig()
{
var instance = new cls1();
cls1.GrantAccess();
}
You should also make cls1 disposable and call .Dispose() on _entities after you're finishied using it.
public class cls1 : IDisposable
{
...
public void Dispose()
{
_entities.Dispose();
}
Put the cls1 instance into a using block, like this:
public void GetCConfig()
{
using(var instance = new cls1())
{
cls1.GrantAccess();
}
}
Finally, the following line is not needed, because _entities will always be null at the beginning of the constructor.
if (_entities == null)
{
I'd suggest reading some basic documentation about object oriented programming with c#, for example:
https://msdn.microsoft.com/en-us/library/dd460654.aspx
**I(one instance of a class) want to find out say which class instantiated me?
I have a class C that is instantiated by Class A and Class B. I want to find out which class instantiated me, so that I can access the variable from that class.
The usual way is to pass in an identifier that hey I am from class A and pass in the variable x in the constructor for the C to consume in the way appropriate for it.
**
eg:
public Class A
{
public int x;
public A()
{
C c = new C();
}
}
public Class B
{
public int x;
public B()
{
C c = new C();
}
}
public Class C
{
public CMethod()
{
// I want Access int x from the class that instantiated me.
if I know its B then B.x ...
}
}
There is no way to know without some hacking (see below). This looks like a case for an interface…
Classes A and B define HasX which has a getX() method. You can pass either class to the constructor of C which expects any class which implements HasX. Then C can call getX on either object and it doesn't need to know which type it actually is, but it will get the appropriate X value.
public interface HasX {
public int getX();
}
public class A implements HasX {
private int x;
public A()
{
C c = new C(this);
}
public int getX() {
return x;
}
}
public class B implements HasX {
private int x;
public B() {
C c = new C(this);
}
public int getX() {
return x;
}
}
public class C {
HasX hasX;
public C(HasX hasX) {
this.hasX = hasX;
}
public void doStuff() {
int x = hasX.getX();
}
}
To answer you original question though, the object which created an object is not stored anywhere… but you can do some hacking when C is constructed for find out the class. Here is some code I once used for a Logging implementation which could detect who was the caller by looking back along the stracktrace of a Throwable. Again, this is not good practice, but you asked so… :)
From: https://github.com/slipperyseal/atomicobjects/blob/master/atomicobjects-lang/src/main/java/net/catchpole/trace/PrintTrace.java
public C() {
String whoCalledMe = whereAmI(new Throwable());
}
private String whereAmI(Throwable throwable) {
for (StackTraceElement ste : throwable.getStackTrace()) {
String className = ste.getClassName();
// search stack for first element not within this class
if (!className.equals(this.getClass().getName())) {
int dot = className.lastIndexOf('.');
if (dot != -1) {
className = className.substring(dot + 1);
}
return className + '.' + ste.getMethodName();
}
}
return "";
}
You might want to edit this to simply return the class name, or even do a Class.forName() to resolve the actual class.
If you want the actual objects, and there is only ever 1 of each class, you could out the objects in a Map keyed on classname. But gee what a mess around :)
i have one doubt if if we have two classes with same method,object of class doesnt know which method to call this situtation we use interface? but how interface know which class method to call,how to apply interface ,i have some code plz check and tell me?
namespace IntExample
{
interface Iinterface
{
public void add();
public void sub();
}
public partial class Form1 : Form,Iinterface
{
public Form1()
{
InitializeComponent();
}
public void add()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a + b;
txtresult.Text = c.ToString();
}
public void sub()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a - b;
txtresult.Text = c.ToString();
}
private void btnadd_Click(object sender, EventArgs e)
{
add();
}
private void button2_Click(object sender, EventArgs e)
{
sub();
}
class cl2 : Form1,Iinterface
{
public void add()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a + b;
txtresult.Text = c.ToString();
}
}
}
}
An interface is an abstraction, one that allows you to perform polymorphism without the need for inheritance. As such, an "interface variable" holds an instance of a concrete class, and the current instance's class is always used for method lookups by the interface as long as the variable contains that instance.