Here is my scenario: I am trying to get a value from frontend using AJAX and then want to use this in a non-static method for some calculations. But I am getting an error:
Object reference not set to an instance of an object
I know how to use non-static method/data members in a static method by creating obrect Reference that I did but still error is same.
Code:
[WebMethod]
[WebScript]
public static string refAssignments(getVal rf)
{
string value = rf.valueFromAJAX;
MyClass obj = new MyClass();
string result = obj.analyse(value);
}
Here Analyse() is a non-static method all I want is to use this method inside the static method refAssignments.
I tried earlier questions but wasn't successful! Can someone point where I am doing wrong
The problem isn't relevant with the Analyse method is non-static or not. Probably, rf object is null. Check the rf object;
if (rf != null)
{
string value = rf.valueFromAJAX;
MyClass obj = new MyClass();
string result = obj.analyse(value);
}
else
{
//Do something
}
Related
If I am passing an object to a method, why should I use the ref keyword? Isn't this the default behaviour anyway?
For example:
class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
}
static public void DoSomething(TestRef t)
{
t.Something = "Bar";
}
}
public class TestRef
{
public string Something { get; set; }
}
The output is "Bar" which means that the object was passed as a reference.
Pass a ref if you want to change what the object is:
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(ref t);
void DoSomething(ref TestRef t)
{
t = new TestRef();
t.Something = "Not just a changed t, but a completely different TestRef object";
}
After calling DoSomething, t does not refer to the original new TestRef, but refers to a completely different object.
This may be useful too if you want to change the value of an immutable object, e.g. a string. You cannot change the value of a string once it has been created. But by using a ref, you could create a function that changes the string for another one that has a different value.
It is not a good idea to use ref unless it is needed. Using ref gives the method freedom to change the argument for something else, callers of the method will need to be coded to ensure they handle this possibility.
Also, when the parameter type is an object, then object variables always act as references to the object. This means that when the ref keyword is used you've got a reference to a reference. This allows you to do things as described in the example given above. But, when the parameter type is a primitive value (e.g. int), then if this parameter is assigned to within the method, the value of the argument that was passed in will be changed after the method returns:
int x = 1;
Change(ref x);
Debug.Assert(x == 5);
WillNotChange(x);
Debug.Assert(x == 5); // Note: x doesn't become 10
void Change(ref int x)
{
x = 5;
}
void WillNotChange(int x)
{
x = 10;
}
You need to distinguish between "passing a reference by value", and "passing a parameter/argument by reference".
I've written a reasonably long article on the subject to avoid having to write carefully each time this comes up on newsgroups
In .NET when you pass any parameter to a method, a copy is created. In value types means that any modification you make to the value is at the method scope, and is lost when you exit the method.
When passing a Reference Type, a copy is also made, but it is a copy of a reference, i.e. now you have TWO references in memory to the same object. So, if you use the reference to modify the object, it gets modified. But if you modify the reference itself - we must remember it is a copy - then any changes are also lost upon exiting the method.
As people have said before, an assignment is a modification of the reference, thus is lost:
public void Method1(object obj) {
obj = new Object();
}
public void Method2(object obj) {
obj = _privateObject;
}
The methods above does not modifies the original object.
A little modification of your example
using System;
class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
}
static public void DoSomething(TestRef t)
{
t = new TestRef();
t.Something = "Bar";
}
}
public class TestRef
{
private string s;
public string Something
{
get {return s;}
set { s = value; }
}
}
Since TestRef is a class (which are reference objects), you can change the contents inside t without passing it as a ref. However, if you pass t as a ref, TestRef can change what the original t refers to. i.e. make it point to a different object.
With ref you can write:
static public void DoSomething(ref TestRef t)
{
t = new TestRef();
}
And t will be changed after the method has completed.
Think of variables (e.g. foo) of reference types (e.g. List<T>) as holding object identifiers of the form "Object #24601". Suppose the statement foo = new List<int> {1,5,7,9}; causes foo to hold "Object #24601" (a list with four items). Then calling foo.Length will ask Object #24601 for its length, and it will respond 4, so foo.Length will equal 4.
If foo is passed to a method without using ref, that method might make changes to Object #24601. As a consequence of such changes, foo.Length might no longer equal 4. The method itself, however, will be unable to change foo, which will continue to hold "Object #24601".
Passing foo as a ref parameter will allow the called method to make changes not just to Object #24601, but also to foo itself. The method might create a new Object #8675309 and store a reference to that in foo. If it does so, foo would no longer hold "Object #24601", but instead "Object #8675309".
In practice, reference-type variables don't hold strings of the form "Object #8675309"; they don't even hold anything that can be meaningfully converted into a number. Even though each reference-type variable will hold some bit pattern, there is no fixed relationship between the bit patterns stored in such variables and the objects they identify. There is no way code could extract information from an object or a reference to it, and later determine whether another reference identified the same object, unless the code either held or knew of a reference that identified the original object.
This is like passing a pointer to a pointer in C. In .NET this will allow you to change what the original T refers to, personally though I think if you are doing that in .NET you have probably got a design issue!
By using the ref keyword with reference types you are effectively passing a reference to the reference. In many ways it's the same as using the out keyword but with the minor difference that there's no guarantee that the method will actually assign anything to the ref'ed parameter.
ref mimics (or behaves) as a global area just for two scopes:
Caller
Callee.
If you're passing a value, however, things are different. You can force a value to be passed by reference. This allows you to pass an integer to a method, for example, and have the method modify the integer on your behalf.
I can declare an Action and pass it a method on an instance object which modifies that object's internal state, then call the method and see that the private instance variables have changed. But if I create the Action, then null out the object it has a reference to a method on I don't get a null reference exception when I invoke the Action, but obviously I do if I try to access the object.
How can it be changing anything if there is nothing there to change?
A contrived example where I create a builder object which has a public void BuildWall method which just increments the number of walls it has built (a private integer variable). Why can I call buildWallAction after I have set builder to null or else how is the Action modifying the object if the object doesn't need to exist in order to call the action?
Thanks in advance :)
class Program
{
static void Main(string[] args)
{
Builder builder = new Builder("Jim");
Console.WriteLine(builder.ToString());
Action buildWallAction = builder.BuildWall;
builder = null; //no more builder to change via BuildWall()
//starts work
buildWallAction(); //these calls modify _wallsBuilt on the builder object
buildWallAction(); //but if we set it to null we can still call them just fine
Console.WriteLine(builder.GetBuildingStatus()); //we will only get an exception here if builder is null
Console.ReadKey();
}
}
public class Builder
{
private string _name;
private int _wallsBuilt;
public Builder(string name)
{
_name = name;
_wallsBuilt = 0;
}
public void BuildWall()
{
_wallsBuilt++;
}
public string GetBuildingStatus()
{
string msg = $"{_name} has built {_wallsBuilt} walls.";
return msg;
}
}
Your builder variable isn't the instance, it is a reference to the instance. So setting the variable to null, doesn't 'erase' the instance, you only get rid of the reference so you cannot access it anymore.
The buildWallAction variable is a reference to the method BuildWall of the instance. This is no way directly related to the builder variable. Setting the builder variable to null doesn't do anything to the buildWallAction variable.
When I am updating my obj as null its output is 30 but no exception but when I am updating obj.Age = 25 output is 25.
I am not getting the idea what is happening behind the scene.
Can someone explain why this is happening?
public class A
{
public int age;
}
class Program
{
public static void Test(A obj)
{
//obj = null;
//obj.age = 25;
}
static void Main(string[] args)
{
try
{
A obj = new A();
obj.age = 30;
Test(obj);
Console.WriteLine(obj.age);
}
catch (Exception)
{
throw;
}
}
}
Notice the method signature -
public static void Test(A obj)
The parameter is not passed as ref. When the reference types are passed as parameter, without specifying as ref. You can change the properties values within the object, but you cannot assign the object to point it to another memory location.
In simple words you cannot do -
obj = null OR obj = new A() OR obj = instanceOfAnotherObject
To be able to even change the object, you need to change the method signature and pass obj by ref -
public static void Test(ref A obj)
When you do obj = null; then you do not set the object to null but the reference to that object to null. As in your method Test the parameter is a new reference to the passed object, it does not affect the obj reference in Main and so setting obj to null in Test has only an effect in that method.
To do / see what you want you may want to change the parameter of Test to a ref parameter like so
public static void Test(ref A obj)
and then call Test like so
...
A obj = new A();
obj.age = 30;
Test(ref obj);
...
as now you actually modify the obj reference of the Main method.
When you do obj.age = 25; in Test (of course without setting obj to null in front of it) then you modify the same object as obj in Main points to and so when writing the age to the console you will see 25.
That is possible because it was passed by reference - if you replace A with e.g. int and pass that around then changing its value in Test will not be reflected in the output of Main as integers are passed by value. You may find reading this page and the subsequent pages to it helpful
If I am passing an object to a method, why should I use the ref keyword? Isn't this the default behaviour anyway?
For example:
class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
}
static public void DoSomething(TestRef t)
{
t.Something = "Bar";
}
}
public class TestRef
{
public string Something { get; set; }
}
The output is "Bar" which means that the object was passed as a reference.
Pass a ref if you want to change what the object is:
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(ref t);
void DoSomething(ref TestRef t)
{
t = new TestRef();
t.Something = "Not just a changed t, but a completely different TestRef object";
}
After calling DoSomething, t does not refer to the original new TestRef, but refers to a completely different object.
This may be useful too if you want to change the value of an immutable object, e.g. a string. You cannot change the value of a string once it has been created. But by using a ref, you could create a function that changes the string for another one that has a different value.
It is not a good idea to use ref unless it is needed. Using ref gives the method freedom to change the argument for something else, callers of the method will need to be coded to ensure they handle this possibility.
Also, when the parameter type is an object, then object variables always act as references to the object. This means that when the ref keyword is used you've got a reference to a reference. This allows you to do things as described in the example given above. But, when the parameter type is a primitive value (e.g. int), then if this parameter is assigned to within the method, the value of the argument that was passed in will be changed after the method returns:
int x = 1;
Change(ref x);
Debug.Assert(x == 5);
WillNotChange(x);
Debug.Assert(x == 5); // Note: x doesn't become 10
void Change(ref int x)
{
x = 5;
}
void WillNotChange(int x)
{
x = 10;
}
You need to distinguish between "passing a reference by value", and "passing a parameter/argument by reference".
I've written a reasonably long article on the subject to avoid having to write carefully each time this comes up on newsgroups
In .NET when you pass any parameter to a method, a copy is created. In value types means that any modification you make to the value is at the method scope, and is lost when you exit the method.
When passing a Reference Type, a copy is also made, but it is a copy of a reference, i.e. now you have TWO references in memory to the same object. So, if you use the reference to modify the object, it gets modified. But if you modify the reference itself - we must remember it is a copy - then any changes are also lost upon exiting the method.
As people have said before, an assignment is a modification of the reference, thus is lost:
public void Method1(object obj) {
obj = new Object();
}
public void Method2(object obj) {
obj = _privateObject;
}
The methods above does not modifies the original object.
A little modification of your example
using System;
class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
}
static public void DoSomething(TestRef t)
{
t = new TestRef();
t.Something = "Bar";
}
}
public class TestRef
{
private string s;
public string Something
{
get {return s;}
set { s = value; }
}
}
Since TestRef is a class (which are reference objects), you can change the contents inside t without passing it as a ref. However, if you pass t as a ref, TestRef can change what the original t refers to. i.e. make it point to a different object.
With ref you can write:
static public void DoSomething(ref TestRef t)
{
t = new TestRef();
}
And t will be changed after the method has completed.
Think of variables (e.g. foo) of reference types (e.g. List<T>) as holding object identifiers of the form "Object #24601". Suppose the statement foo = new List<int> {1,5,7,9}; causes foo to hold "Object #24601" (a list with four items). Then calling foo.Length will ask Object #24601 for its length, and it will respond 4, so foo.Length will equal 4.
If foo is passed to a method without using ref, that method might make changes to Object #24601. As a consequence of such changes, foo.Length might no longer equal 4. The method itself, however, will be unable to change foo, which will continue to hold "Object #24601".
Passing foo as a ref parameter will allow the called method to make changes not just to Object #24601, but also to foo itself. The method might create a new Object #8675309 and store a reference to that in foo. If it does so, foo would no longer hold "Object #24601", but instead "Object #8675309".
In practice, reference-type variables don't hold strings of the form "Object #8675309"; they don't even hold anything that can be meaningfully converted into a number. Even though each reference-type variable will hold some bit pattern, there is no fixed relationship between the bit patterns stored in such variables and the objects they identify. There is no way code could extract information from an object or a reference to it, and later determine whether another reference identified the same object, unless the code either held or knew of a reference that identified the original object.
This is like passing a pointer to a pointer in C. In .NET this will allow you to change what the original T refers to, personally though I think if you are doing that in .NET you have probably got a design issue!
By using the ref keyword with reference types you are effectively passing a reference to the reference. In many ways it's the same as using the out keyword but with the minor difference that there's no guarantee that the method will actually assign anything to the ref'ed parameter.
ref mimics (or behaves) as a global area just for two scopes:
Caller
Callee.
If you're passing a value, however, things are different. You can force a value to be passed by reference. This allows you to pass an integer to a method, for example, and have the method modify the integer on your behalf.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why can I only access static members from a static function?
While I was trying to call a normal method from inside a static method I got the error:
An object reference is required for the non-static field, method, or property
So this means I need to create the object of the Class and then call the nonstatic method. If I want to call the method directly then I have to declare that method as Static.
But , in this scenario , the calling method and called method belong to same class. So Why do I need to create an object while calling from a Static Method , while I can call a non-static method from non static method.
Ex:
class Program
{
//public void outTestMethod(int x,out int y)
//{
// y = x;
//}
static void Main(string[] args)
{
int a = 10;
int b = 100;
outTestMethod(a,out b);
}
private void outTestMethod(int x, out int y)
{
y = x;
}
}
Error:An object reference is required for the non-static field, method, or property
Static methods can call instance methods - but you need to have an instance on which to call them. It doesn't matter where that instance comes from particularly, so for example:
int a = 10;
int b = 100;
Program program = new Program();
program.outTestMethod(a,out b);
Instance methods are associated with a particular instance of the type, whereas static methods are associated with the overall type instead - and the same is true for other kinds of members. So to call an instance method, you need to know which instance you're interested in. For example, it would be meaningless to have:
string name = Person.Name;
because you need to know which person you're talking about:
Person person = FetchPersonFromSomewhere();
string name = person.Name;
... that makes much more sense.
Typically instance methods use or modify the state of the instance.
Consider it this way.
A static method is the button outside a bank of elevators. Anyone can see it and push it, and make something happen (i.e. one of the elevators will arrive at that floor).
The non-static methods are the buttons inside a specific elevator. They manipulate THAT elevator (and none of the others).
A non-static method is also called an instance method. This means there (usually) is a chunk of data, specific to the instance (object) that the method operates on.
You can't call a non static or instance method from a static method because it wouldn't know which instance or object to operate on.
Because there is no instance to call the method from. YOu should create possibly another class and test on that:
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 100;
Test testclass = new Test();
testclass.outTestMethod(a,out b);
}
}
class Test
{
public void outTestMethod(int x, out int y)
{
y = x;
}
}
do you understand the difference between instance method and static method?
an instance method has access to the this object even if it's not passed in as parameter, in fact it's like if it was an invisible parameter of the same type of the class passed for you by the framework.
a static method does not have that this object and cannot call instance methods because it does not have anything to pass for that this in the invisible way...
sounds like a joke but this is the way I see it :)